2014-04-06 5 views
2

사용자가 버튼을 클릭 할 때 대화 상자를 만들려고하지만 오류가 계속 발생합니다. 이것은 내가 가진 코드입니다.Ajax가있는 장고 클래스 기반 뷰?

참고로 django-braces를 사용하여 ajax 호출을 수신합니다.

보기 :

class UserRegistration(braces.AjaxResponseMixin, CreateView): 
    form_class = UserRegistrationForm 
    template_name = "registration_form.html" 

    def get_ajax(self, request, *args, **kwargs): 
     context = self.get_context_data(**kwargs) 
     rendered = render_to_string(self.template_name, context_instance=context) 
     return HttpResponse(rendered) 

자바 스크립트 :

$("#signup").on("click", function(){ 
    $("body").append("<div id='dialog' title='Register'></div>"); 
    $("#dialog").dialog({ 
     height: 'auto', 
     width: 'auto', 
     modal: true, 
     autoOpen: false 
    }); 

    $.ajax({ 
     url: '/signup/', 
     data: {}, 
     type: 'GET', 
     success: function(data){ 
      $("#dialog").html(data); 
      $("#dialog").dialog("open"); 
     }, 
     error: function(error) { 
      alert("failure"); 
     } 
    }); 
}); 

나는 그것이 단순히 같은 동일 rendered을 설정하는 경우 때문에 render_to_string 함께 할 수있는 뭔가 알고이 일 것 "이 일부 텍스트가" ,하지만 내가 뭘 잘못하고 있는지 모르겠다.

답변

3

render_to_string에있는 context_instance 매개 변수는 Context 인스턴스를, get_context_data은 사전을 반환합니다. 이 문제를 해결할 수있는 방법은 여러 가지가 있습니다.

1) Context 인스턴스 (예 : RequestContext)를 제공하십시오.

def get_ajax(self, *args, **kwargs): 
    context = self.get_context_data(**kwargs) 
    rendered = render_to_string(self.template_name, dictionary=context) 
    return HttpResponse(rendered) 

3 : dictionary 매개 변수를 사용하여, 사전 등의 컨텍스트를 통과

from django.template import RequestContext 

def get_ajax(self, *args, **kwargs): 
    context = self.get_context_data(**kwargs) 
    rendered = render_to_string(self.template_name, 
           context_instance=RequestContext(self.request, context)) 
    return HttpResponse(rendered) 

2), • RequestContext 모든 상황에 맞는 프로세서를 실행합니다, 그래서 requestuser 같은 기본 변수는 템플릿을 사용할 수 있습니다) 렌더링 된 문자열을 HttpResponse 객체로 전달하는 중이므로 을 건너 뛰고 대신 render을 사용할 수 있습니다.

from django.shortcuts import render 

def get_ajax(self, *args, **kwargs): 
    context = self.get_context_data(**kwargs) 
    return render(self.request, self.template_name, context) 
관련 문제