使用Ajax的Django类视图?

2 投票
1 回答
2633 浏览
提问于 2025-04-18 01:38

我想在用户点击按钮时弹出一个对话框,但我总是遇到错误。这是我写的代码。

顺便提一下,我在使用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)

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");
        }
    });
});

我知道问题出在render_to_string上,因为如果我把rendered直接设置成像“这是一段文本”这样的内容,它就能正常工作,但我不太确定我哪里出错了。

1 个回答

4

render_to_string 这个函数里,context_instance 参数需要一个 Context 实例,而 get_context_data 返回的是一个字典。你可以用几种方法来解决这个问题:

1) 提供一个 Context 实例,最好是 RequestContext。使用 RequestContext 的好处是它会执行所有的上下文处理器,这样像 requestuser 这些默认变量就可以在模板中使用了:

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) 也可以把上下文作为字典传递,使用 dictionary 参数:

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) 由于你只是把渲染后的字符串放入一个 HttpResponse 对象中,你可以直接使用 render,跳过 render_to_string

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)

撰写回答