Show form errors (non field errors)

Posted: February 5th, 2010 | Author: | Filed under: Django | Tags: , , , | 1 Comment »

In the current Django version it is possible to implement form validation by overriding the clean() function.
For instance a ContactForm:

class ContactForm(forms.Form):
    # ... fields...
   field1 = forms.IntegerField()

   def clean(self)
       cleaned_data = self.cleaned_data
       f = cleaned_data.get('field1')
       if f > 10:
          raise forms.ValidationError("Did you just enter more than 10?")
       return cleaned_data # Never forget this otherwise you will end up with empty request.POST in the views.py.

In order to show that “Did you just enter more than 10″ error in the template:

<!-- assuming that you have form as ContactForm. -->
{{ form.non_field_errors }}

Validate an instance without POST values

Posted: January 14th, 2010 | Author: | Filed under: Django | Tags: , , , | No Comments »

Sometimes it is useful to validate an instance of a model without having the POST values.
You will ask me why? Well, a form can be filled in different steps and be validated at the final step.
This is where it comes handy, validate the Object to see if all the steps are properly completed.

The following example demonstrates how to validate an instance without using the request.POST

from django.db import models
from django import forms

# a simple example of an Article model
class Article(models.Model):
     title = models.CharField(max_length=100)
     body = models.TextField(max_length=400)

# let's create the form from the Article model.
class ArticleForm(forms.ModelForm):
     class Meta:
          model = Article

# an article form with only the title on it.
# we can use this as a step 1, where the user is filling only the title.
class ArticleLessform(forms.ModelForm):
     class Meta:
          model = Article
          fields = ('title', ) # only show the title.
# inside views.py
from your_directory.models import Article, ArticleForm, ArticleLessForm 

def do_something(request):
     # change for the appropriate id.
     article_qs = Article.objects.filter(id=1)

     # get the actual Article object.
     article = article_qs.get()                      

     # all the magic is on this line
     # values() returns a key/values pairs and we use this to simulate a request.POST.
     form = ArticleForm(article_qs.values()[0], instance=article)
     if form.is_valid()
        print 'It seems that the title and body are filled properly.'
     else:
        print 'The Article object did not validate'

You can read more about the values() on the django docs.


Display asterisks for required fields in template

Posted: January 11th, 2010 | Author: | Filed under: Django | Tags: , , , , | 2 Comments »

If you want to display simple asterisks (*) for required fields in Django then the following code is for you.
The trick is to access the field properties inside the template and make a conditional statement.
Here is a simple example of view and template:

# this is inside your views.py
def do_something(request):
      """Display simple form"""
      form = MyForm() # this will be used in the template.
      return render_to_response('template.html', locals())

# this is inside your template.html
{% for field in form %} {{ field }} {% if field.field.required %}(*){% endif %} {% endfor %}

The locals() function is a built in python function