django forms and ajax

后端 未结 3 1935
春和景丽
春和景丽 2021-02-04 22:05

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

  • a form which the user fills and submits many times
  • a chart which updates every time the user submi
3条回答
  •  被撕碎了的回忆
    2021-02-04 22:45

    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)
    

    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)

提交回复
热议问题