【问题标题】:how validate form and show the value of the filled fields?如何验证表单并显示填充字段的值?
【发布时间】:2009-08-09 01:42:50
【问题描述】:

现在我正在学习验证表单,“所有”都在工作,我正在显示空字段的错误,但我有 2 个问题:

  1. 当其他字段出现错误时,如何在填充字段中显示值?例如<input ... value= {{ value }} > 问题是我的字段不是 html 表单字段。
  2. 如何准确地在空白字段上显示错误?

我怎么会有这个:

form.py

class NuevaDiligenciaForm(forms.Form):
    titulo = forms.CharField(max_length=70)    
    tipo = forms.ChoiceField(choices=TIPO)        
    vias= forms.TypedChoiceField(widget=forms.RadioSelect(), choices=CHOICES)

view.py

def add(request):        
    form = NuevaDiligenciaForm()
    errors =[]
    if request.method =='POST': 
        if not request.POST.get('titulo',''):
            errors.append('Titulo es requerido')
        if not request.POST.get('vias',''):
            errors.append('Vias es requerido')
        #if not errors:
    return render_to_response('account/add.html', { 'formulario':form ,'errors':errors},context_instance = RequestContext(request))   

模板.html

{% if errors %}
    <ul>
        {% for error in errors %}
        <li>{{ error }}</li>
        {% endfor %}
    </ul>
{% endif %}

{% if message %}
        <p style="color: red;">{{ message }}</p>
{% endif %}
<form action='.' method='POST' class="nueva-diligencia"> 

{{ formulario.as_p }}

<input type="submit" value="Continuar">
</form>

再次感谢:)

【问题讨论】:

    标签: django django-forms django-validation


    【解决方案1】:

    您的表单代码在这里看起来不错,但您的视图需要更改为:

    def add(request):
    if request.method =='POST':
        form = NuevaDiligenciaForm(request.POST)
        if form.is_valid():
            clean_data = form.cleaned_data
            # Now do something with the cleaned data...
    else:
        form = NuevaDiligenciaForm()
    return render_to_response('account/add.html', { 'formulario': form }
    

    你的模板应该是这样的:

    {% if message %}
    <p style="color: red;">{{ message }}</p>
    {% endif %}
    <form action='.' method='POST' class="nueva-diligencia"> 
        {{ formulario.as_p }}
        <input type="submit" value="Continuar">
    </form>
    

    现在发生的情况是,如果 POST 中有错误数据,form.is_valid() 将失败,视图将返回经过验证的表单,其中包含错误字段旁边的错误。 Django 在这里为您处理所有错误!试试看,如果它按您的预期工作,请告诉我。

    如果您想了解这个简化版本如何/为什么实际上效果更好,这是一个很好的资源:@​​987654321@

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2022-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      相关资源
      最近更新 更多