Django的形式和AJAX形式、Django、AJAX

2023-09-10 16:05:36 作者:今天没吃药感觉自己萌萌哒

我想有两个功能部件创建一个页面:

I'm trying to create a page with two functional parts:

其中用户填写并提交多次形式 图表哪些更新每次用户提交表单时

我使用 Django的形式和的 jQuery的,我不能完全弄清楚如何设计结合在一起的 在提交的形式两种情况之一应该发生,无论是图表(并且仅在图表)更新的,或者,如果有一个形式验证错误,窗体部应该更新用适当的错误消息。所以实际上1 Ajax调用应该更新任何一部分。 我想,而不是整个页面,其中包括其他的只有相关的 DIV 更新(无论是形式或图表) DIV ,标志等静态图形。

I'm using django forms and jQuery and I can't quite figure out how the design fits together. Upon submission of the form one of two things should happen, either the chart (and only the chart) updates or, if there is a form validation error, the form section should update with the appropriate error messages. So actually one Ajax call should update either part. I'd like only the relevant div to update (either form or chart) instead of the entire page which includes the other div, a logo and other static graphics.

面临的挑战之一是,如果形式sumbission进行得很顺利,我想返回一个JSON对象,更新图表,因为我使用的是第三方的制图包,但是如果提交failes返回的内容应是与更新的形式的HTML响应

One of the challenges is that if the form sumbission went well, I'd like to return a JSON object which updates the chart, as I'm using a 3rd party charting package, however if the submission failes the returned content should be an HTML response with the updated form.

什么是正确的模式为这种行为Django的看法? 什么是正确的javascript \ jQuery的模式为这种行为? 如果这种做法是不正确的,这将是另一种方法?

What would be a correct pattern for the django view for this behavior? What would be a correct javascript\jQuery pattern for this behavior? If this approach is not correct, what would be an alternative approach?

推荐答案

您需要激活。例如,使用jQuery:

You need JavaScript. For example, with jQuery:

$('form').submit(function() {
    $.post($(this).attr('action'), $(this).serialize(), function(data, textStatus, jqXHR){
        if (typeof data == 'object') {
            // json was returned, update the chart with the json
        } else {
            // the form had error, the form's html was returned
            $('form').html(data);
        }
    })
})

您可以有这样的蟒蛇观点:

You can have such a python view:

from django.utils import simplejson
from django import shortcuts

def chart_form(request):
    template_full = 'chart_full.html' # extends base.html etc ..
    template_form = 'chart_form.html' # just the form, included by chart_full.html

    if request.method == 'POST':
        form = formClass(request.POST) 
        if form.is_valid():
            // do your chart_data
            chart_data = ....
            return http.HttpResponse(simplejson.dumps(chart_data), mimetype='application/json')
    else:
        form = formClass()

    if request.is_ajax():
        template_name = template_form
    else:
        template_name = template_full

    return shortcuts.render(template_name, {'form': form}, request)

请注意:这是行不通的,如果你的表单包含文件中的字段。在这种情况下,依赖于这个插件: http://jquery.malsup.com/form/ (功能ajaxSubmit会)

Note: that won't work if your form contains file fields. In that case, rely on this plugin: http://jquery.malsup.com/form/ (function ajaxSubmit)