【问题标题】:update a django form with jquery/ajax使用 jquery/ajax 更新 django 表单
【发布时间】:2013-09-19 17:41:53
【问题描述】:

我想在我的下拉列表的更改事件中更新一个表单。

这是我的看法:

from django.utils import simplejson
response_dic={}
#drop down list
actToValidateId=add_form.cleaned_data['actsToValidate'].pk
act=ActsIdsModel.objects.get(id=actToValidateId)
ids_form = ActsIdsForm(instance=act)

ids_form_dic={}
for field in ids_form.fields:
    ids_form_dic[field]=getattr(act, field)
response_dic['ids_form']=ids_form_dic
response_dic['act']=dict([(attr, getattr(act, attr)) for attr in [f.name for f in act._meta.fields]])

return HttpResponse(simplejson.dumps(response_dic), mimetype="application/json")

这里是javascript代码:

function display_act_ids(choice)
{
    $form=$('#act_ids_form');
    var form_data = $form.serialize();
    $.ajax
    ({
        url: $form.attr('action'),
        type: 'POST',
        dataType: 'json',
        data: form_data,
        success: function(result)
        {
            alert(result.ids_form.fileNoCelex);
        }
    });

    //don't submit the form
    return false;
}

现在,有两个问题:

1/ 如果我想为我的表单控件分配相应的值,我可以更新成功函数如下:

$("#myfield").val(result.ids_form.myfield);

但是如果我有很多字段要填写怎么办?是否有自动执行此操作的功能?也许一个循环会做......

2/我的主要问题:我在我的模板(不是我的表单)的很多地方使用我的行为实例(和其他变量)。例如:

{% if act.councilPath %}
    <div class="row-fluid">{{ act.councilPath }}</div>
{% endif %}

这样的话,是不可能使用ajax的。这意味着我必须重写我的模板才能让它工作。例如:

<div id="council_path" class="row-fluid"></div>

在我的成功函数中:

 $("#council_path").html(result.act.councilPath);

这将是很长的更新。有没有更好的办法,比如 ajax “post and load”?

如果我不清楚,请告诉我。

【问题讨论】:

    标签: jquery ajax django forms


    【解决方案1】:

    要使用 jquery/ajax 更新 django 表单,这是我的方法... 三个关键点:将表单模板放在单独的 html 页面中,在视图中使用 render_to_string 并向 ajax 发送 html 响应。

    index.html 页面:

    {% extends "base.html" %}
    
    {% block content %}
        <!-- you can put here everything that doesn't need to be updated (text, css inclusion, etc.) -->
        <!-- act validation form -->
        <form id="act_ids_form"  class="form-inline" action="{% url act_ids %}" method="post">{% csrf_token %}
                <!-- drop down list -->
                <div id="actsToValidateChoice" class="fieldWrapper">
                      {{ add_form.actsToValidate.errors }}
                      {{ add_form.actsToValidate }}
                </div>
                <!-- div to update the part of the form that must be updated -->
                <div id="act_ids_form_div">{% include form_template %}</div>
        </form>
    
    {% 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:

    <!-- act ids form -->
    <!-- put here everything that must be updated on the change of your drop down list -->
    <div class="row-fluid">{{ ids_form.non_field_errors }}</div>
    
    {% if act.councilPath %}
            <div class="row-fluid"><a class="info_msg" href="{{act.councilPath}}" target="_blank">{{ displayName.councilPath }}</a></div>
    {% endif %}
    
    <table class="table table-bordered table-hover table-condensed span12">
            <tr>
                {% for field in ids_form %}
                    <td>
                        <div class="fieldWrapper">
                            {{ field.errors }}
                            {{ field }}
                        </div>
                    </td>
                {% endfor %}
            </tr>
    </table>
    

    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 调用:

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

    瞧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-26
      • 2014-11-25
      • 2020-04-18
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多