update a django form with jquery/ajax

后端 未结 1 1518
花落未央
花落未央 2021-02-06 13:31

I want to update a form on the change event of my drop down list.

Here is my view:

from django.utils import simplejson
response_dic={}
#drop down list
ac         


        
1条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 14:16

    To update a django form with jquery/ajax, here is my method... Three key points: put your form template in a separate html page, use render_to_string in your view and send an html response to ajax.

    index.html page:

    {% extends "base.html" %}
    
    {% block content %}
        
        
        
    {% csrf_token %}
    {{ add_form.actsToValidate.errors }} {{ add_form.actsToValidate }}
    {% include form_template %}
    {% endblock %}

    forms.py:

    class ActsAddForm(forms.Form):
            #drop down list      
            actsToValidate=forms.ModelChoiceField(queryset=ActsIdsModel.objects.filter(validated=0), empty_label="Select an act to validate", widget=forms.Select(attrs={'onchange': 'display_act_ids()'}))
    

    form.html:

    
    
    
    {{ ids_form.non_field_errors }}
    {% if act.councilPath %} {% endif %} {% for field in ids_form %} {% endfor %}
    {{ field.errors }} {{ field }}

    urls.py:

    from django.conf.urls import patterns, url
    
    urlpatterns = patterns('actsIdsValidation.views',
        url(r'^/?$', 'act_ids', name='act_ids'),
        url(r'^form.html$', 'act_ids', name='act_ids'),
    )
    

    views.py:

    def act_ids(request):
        response_dic={}
        #html page of the form
        form_template='actsIdsValidation/form.html'
    
        if request.method == 'POST':
            #if drop down list not empty
            if request.POST["actsToValidate"]!="":
                #add form: contains the drop down list only
                add_form = ActsAddForm(request.POST);
                actToValidateId=request.POST["actsToValidate"].pk
                act=ActsIdsModel.objects.get(id=actToValidateId)
                ids_form = ActsIdsForm(instance=act)
                response_dic['ids_form']=ids_form
                response_dic['act']=act
    
                return HttpResponse(render_to_string(form_template, response_dic, RequestContext(request)))
    
        #GET
        #unbound ids_form
        response_dic['ids_form'] = ActsIdsForm()
        response_dic['add_form'] = ActsAddForm()
        response_dic['form_template'] = form_template
        return render_to_response('actsIdsValidation/index.html', response_dic, context_instance=RequestContext(request))
    

    Ajax call:

    function display_act_ids()
    {
        $form=$('#act_ids_form');
        var datastring = $form.serialize();
        $.ajax({
            type: "POST",
            url: $form.attr('action'),
            dataType: 'html',
            data: datastring,
            success: function(result)
            {
                /* The div contains now the updated form */
                $('#act_ids_form_div').html(result);
            }
        });
    
        //don't submit the form
        return false;
    }
    

    Voila !

    0 讨论(0)
提交回复
热议问题