javascript - Django class-based views with ajax? -
i'm trying make dialog when user clicks button, keep getting error. code have.
for note, i'm using django-braces catch ajax calls.
view:
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)
javascript:
$("#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"); } }); });
i know it's render_to_string
because if set rendered
equal "this text" it'll work, i'm not sure i'm doing wrong.
the context_instance
parameter in render_to_string
expects context
instance, while get_context_data
returns dictionary. there several ways can solve this:
1) provide context
instance, preferably requestcontext
. requestcontext
execute context processors, default variables request
, user
available template:
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) pass context dictionary, using dictionary
parameter:
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) you're passing rendered string httpresponse
object, can skip render_to_string
, , use render
instead:
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)
Comments
Post a Comment