views:

85

answers:

1

Hi guys, now im learning to validate form, "all" is working, im showing the erros of empty fields, but i have 2 questions:

  1. how ill show the value in the filled fields when there are errors in another fields?, like <input ... value= {{ value }} > the problem is that my fields are not html forms fields.
  2. how ill show the error exactly over the empty fields?

how i have this:

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))

template.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>

Thanks again :)

A: 

You form code looks fine here but your view needs to change to this:

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 }

and your template should look like this:

{% 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>

Now what happens is that if there is bad data from the POST, form.is_valid() will fail and the view will return the validated form, which will include errors next to fields that have them. Django takes care of all the error handling for you here! Try it out and let me know if it works as you expect it to.

This is a pretty good resource if you'd like to see how/why this simplified version actually works better: http://www.djangobook.com/en/2.0/chapter07/

John Debs
Thanks for replay
Asinox