Django - 如何在表单验证中记住值并显示错误?

时间:2013-01-07 18:47:02

标签: django django-forms django-validation

我没有得到如何记住值并在表单验证中显示错误。

这是我的代码:

template.html:

<form method="post" action="/submeter/anuncio/">{% csrf_token %}
    {{form_main.as_p}}
    {{form_bicyclead.as_p}}
    {{form_bicycleadcategory.as_p}}
    {{form_bicycleaditemkindandpropertyvalueform.as_p}}
    <input type="hidden" name="section" value="5" />
    <input type="submit">
</form>

views.py:

def submit_ad_view(request):
    if request.method == 'POST':      
        model_main = Main()
        model_main.section = Section.objects.get(pk=request.POST['section'])
        model_main.user = request.user

        model_bicyclead = BicycleAd()
        model_bicyclead.bicycleadtype = BicycleAdType.objects.get(pk=2)
        model_bicyclead.bicycleaditemkind = BicycleAdItemKind.objects.get(pk=4)
        model_bicyclead.bicycleadcondition = BicycleAdCondition.objects.get(pk=2)
        model_bicyclead.city = GeonamesLocal.objects.get(pk=4803854)


        form_main = MainForm(request.POST, instance = model_main)
        form_bicyclead = BicycleAdForm(request.POST, instance = model_bicyclead)
        form_bicycleadcategory = BicycleAdCategoryForm(request.POST)

        if form_main.is_valid() and form_bicyclead.is_valid() and form_bicycleadcategory.is_valid():
            main_f = form_main.save()

            bicyclead_f = form_bicyclead.save(commit=False)
            bicyclead_f.main = main_f
            bicyclead_f.save()

            bicycleadcategory_f = form_bicycleadcategory.save(commit=False, rel_obj=model_bicyclead)


            resultado = 'valid'
        else:
            resultado = 'n_valid'

        return render_to_response('app_p/submit_ad.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead, 'form_bicycleadcategory': form_bicycleadcategory, 'form_bicycleaditemkindandpropertyvalueform': form_bicycleaditemkindandpropertyvalueform}, context_instance=RequestContext(request))
    else:
        form_main = MainForm()
        form_bicyclead = BicycleAdForm()
        form_bicycleadcategory = BicycleAdCategoryForm()
        form_bicycleaditemkindandpropertyvalueform = BicycleAdItemKindAndPropertyValueForm()

        return render_to_response('app_p/submit_ad.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead, 'form_bicycleadcategory': form_bicycleadcategory, 'form_bicycleaditemkindandpropertyvalueform': form_bicycleaditemkindandpropertyvalueform}, context_instance=RequestContext(request))   

有关此模板中出现错误的一些线索,并查看未收到错误而不记得表单的值?

最诚挚的问候,

1 个答案:

答案 0 :(得分:1)

我发现您的代码存在两个问题,首先是您用来验证表单的if,当第一个表单返回False时,其余部分将无法验证。

其次,当其中一个表格无效并且您没有向它们传递任何值时,您正在重新创建表单,因此它们最终为空并且带有验证信息。