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.