如何在jquery对话框/模式中处理Django表单提交HTML响应?

时间:2014-01-21 21:17:38

标签: jquery django dialog modal-dialog render-to-string

我尝试从对话框窗口提交表单并在同一对话框窗口中显示响应。现在我尝试使用Django视图返回一个表单(带有Valdiation Errors)作为html字符串。

template = "register.html"
html = render_to_string(template, {'form': form})
return HttpResponse(html, content_type="text/html; charset=utf-8") 

但是我的对话模式中的函数存在一些问题。我错过了使用来自HttpResponse的新html替换“模态/对话框”中内容的部分。

$('#registerform').submit(function(e){
e.preventDefault();
$.post('register', function(data){ 

//somthing is missing here..             
});
return false;    
});

现在不确定格式,但你明白了。如果任何专家能够指导我朝着正确的方向前进,我将是一个快乐的人!感谢

1 个答案:

答案 0 :(得分:0)

这是Django支持的实现: https://github.com/brack3t/django-braces

//Inside your click, event whatever call...
...
// Get the token initialy, this is the way to do it 
// using the jQuery cookie plugin 
var $csrftoken = $.cookie('csrftoken');
$.ajax({
    type: 'POST',
    url: '/your/post/url/',
    crossDomain: false,
    beforeSend: function(xhr) {
        xhr.setRequestHeader("X-CSRFToken", $csrftoken);
    },
    success: function(ctx) {
        """
        ctx contains the data your view returns, 
        If you are using Django braces, you could implement the 
        AjaxResponseMixin mixin which allows you to return a dict 
        to the view.
        """
    },
});
...

views.py

class AjaxDosomethingView(JSONResponseMixin, AjaxResponseMixin, View):

    def post_ajax(self, request, *args, **kwargs):
        """
        Do some stuff and create the response object
        """
        myid = request.POST.get('somevar')
        result = MyModel.objects.get(id=myid)
        response = {'id': result.id, 'title': result.title}

        return self.render_json_response(response, 200)