django模板ModelChoiceField长度

时间:2012-12-19 19:13:47

标签: django templates sql-update choicefield

我在模板中使用长度标记来计算下拉列表中的项目数。第一次呈现表单时,长度很好地显示。提交表单并且长度发生更改后,该值不会更新,但下拉列表会更新!为什么? :(

在forms.py中:

lawsToValidate=forms.ModelChoiceField(queryset=LawsIdsModel.objects.filter(validated=0), empty_label="Select a law to validate", widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))

在我的模板中:

{{ form.lawsToValidate.field.choices|length }}
    <form id="lawsIdsForm" action="{% url lawsValidation.views.lawsView %}" method="post">{% csrf_token %}
        {{ form.non_field_errors }}

        {{ form.lawsToValidate.field.choices|length }} laws to validate!

        <div id="lawsToValidateChoice" class="fieldWrapper">
            {{ form.lawsToValidate.errors }}
            {{ form.lawsToValidate }}
        </div>
    </form>

在views.py中:

def lawsView(request):
    responseDic={}
    state="display"
    if request.method == 'POST':
        lawToValidate=request.POST.getlist('lawsToValidate')[0]
        #if a law is selected
        if lawToValidate!="":
            law=LawsIdsModel.objects.get(id=lawToValidate)
            #saves the law
            if 'lawsValidationSaveButton' in request.POST:
                law.validated=True
                form = LawsIdsForm(request.POST, instance=law)
                if form.is_valid():
                    form.save()
                    del form
                    state="saved"
                    responseDic['success']="The law releveAnnee=" + str(law.releveAnnee) + ", releveMois=" + str(law.releveMois) + ", noOrdre=" + str(law.noOrdre) + " has been validated!"
                else:
                    state="ongoing"
            #displays the retrieved information of the law to validate (selection of a law in the drop down list)
            if state!="saved":
                #a law has been selected in the drop down list -> the related information are displayed
                if state=="display":
                    form = LawsIdsForm(instance=law, initial={'lawsToValidate': lawToValidate, 'releveAnnee': law.releveAnnee, 'releveMois': law.releveMois, 'noOrdre': law.noOrdre})
                #an error occured while validating the law -> display of these errors
                elif state=="ongoing":
                    form = LawsIdsForm(request.POST, instance=law, initial={'lawsToValidate': lawToValidate, 'releveAnnee': law.releveAnnee, 'releveMois': law.releveMois, 'noOrdre': law.noOrdre})
                responseDic['form']=form
                responseDic['law']=law
    #~ #if form has not been created yet -> unbound form
    if 'form' not in locals():
        responseDic['form'] = LawsIdsForm()
    return render_to_response('lawsValidation/index.html', responseDic, context_instance=RequestContext(request))

提前谢谢你,

罗曼

1 个答案:

答案 0 :(得分:2)

我认为你遇到过issue 18066。它被关闭为“需求信息”,但它看起来像是一个错误。

作为解决方法,请尝试

{{ form.lawsToValidate.field.choices.queryset.all|length }}