简体   繁体   中英

Django class-based views with ajax?

I'm trying to make a dialog when the user clicks a button, but I keep getting an error. This is the code I have.

For note, I'm using django-braces to 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 something to do with render_to_string because if I simply set rendered equal to something like "This is some text" it'll work, but I'm not sure what I'm doing wrong.

The context_instance parameter in render_to_string expects a Context instance, while get_context_data returns a dictionary. There are several ways you can solve this:

1) Provide a Context instance, preferably a RequestContext . A RequestContext will execute all context processors, so default variables like request and user are available to the 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 the context as a dictionary, using the 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) As you're just passing the rendered string into a HttpResponse object, you can skip the render_to_string , and 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM