Sunday, 25 August 2013

Django Model Forms Example

The Django documentation on Model Forms is thorough, but sometimes you want a simple example to explain the concept.   Here's one:

Model forms are used for the majority of forms in Django.  They're forms based on a model.  

Model on which the ModelForm is based:

class notification(models.Model):
    report_type = models.ForeignKey( 'report_type')
    event_type = models.ForeignKey( 'event_type')
    client_type = models.ForeignKey( 'client_type')
    email_addresses = models.TextField( 'Email Addresses (; separated)', null=True , max_length=500)

ModelForm:

from django.forms import ModelForm
from myapp.models import notification
from django.contrib.auth.models import User
from django.db.models import Q
from django.core.exceptions import ValidationError
import logging
log = logging.getLogger(__name__)

   
class notificationForm(ModelForm):   
    class Meta:
        model = Notification
    def clean_email_addresses(self):
        # check the email addresses are all for a registered user
        emails = self.cleaned_data['email_addresses']
        emaillist = emails.split( ";")
        if emaillist is not None:
            for e in emaillist:
                users = User.objects.filter(Q(email=e))
                if not users:
                    raise ValidationError( 'Each email address entered must be for a registered user of X-GenCA')
        return emails



View using the ModelForm:

# Create your views here.
from notification.forms import notificatioForm
from myapp.models import Notification
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
import logging
log = logging.getLogger(__name__)
#command line debugging:
#import pdb; pdb.set_trace()

@login_required
def create_notification(request, template_name='notification/save.html' ):
    form = notificationForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect( '/')
   
    return render(request, template_name, {'form':form,'notification' :Notification})


Template (save.html):

{% extends "base.html" %}
<h1 align="center">Create Notification</h1>
<form method="post" action= ".">
{% csrf_token %}
<div style="text-align: center;">
    {{ form.as_p }}
    <input type="submit" value= "Submit Form"/>
    </div>
</form>


URL pointing to View:

url(r'^create/$', views.create_notification), 
 
 
 
 The clean methods in the ModelForm can be used to add any business logic you require to validate the fields.  In the example above it checks the email addresses are those for registered users of the system.


No comments:

Post a Comment