Question

I want to display my non_field_erors in my template. So far, I can display all kind of errors of my forms with:

-> base.html

{% if form.errors %}
    {% for field in form %}
         {% if field.errors %}
         <div class="ui-state-error ui-corner-all notification" > 
        <p>
           <span class="ui-icon ui-icon-alert"></span>
           {{ field.label_tag }}:{{ field.errors|striptags }}
               <a class="hide" onClick="hideBar(this)">hide</a>
            </p>
        </div>  
         {% endif %}                            
    {% endfor%}
{% endif %}

AND

{{ form.non_field_errors }}

I've added a new form which has only an IntegerField:

class MerchantForm(forms.ModelForm):
    price =  forms.IntegerField(widget=forms.TextInput(attrs={'class':'small'}))

    def clean_price(self):
        price = self.cleaned_data.get('price')
        if price == 120:
           raise forms.ValidationError('error blah.')
        return price

When I post price as 120, I don't get any validation errors in my page.

And my view is:

def bid(request,product_slug):
    .
    .
    form = MerchantForm()
    context = RequestContext(request,{
                'form':form,
                                 ....
                    })

    if request.method == 'POST':
        form = MerchantForm(request.POST)
        if form.is_valid():
             return HttpResponse('ok')
  #     else:
  #          return HttpResponse(form.errors.get('__all__'))
   return render_to_response('bid.html',context_instance=context)

I can retrieve the error with commented lines but I don't want to do that in views.py. Any ideas ?

Was it helpful?

Solution

Oh dear.

First of all, why are you asking about non_field_errors when the code snippet you post clearly has the error as being raised in clean_price, and therefore is associated with ths price field?

Secondly, your view code is upside down. You create an empty form instance, and add it to the context. Then you create another form instance, bound to the POST data, but don't put it into the context. So the template never sees the bound form, so naturally you never see any validation errors in the template.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top