Forms Part 3: Model Based Forms

Model forms really helps to show the power behind Django. When all it takes is to define a model and then attach the model object to a form object and poof you have a form, I call that winning. In this video we will go over using your models you already have to create forms to save you time, heartache, and code.
Note: verifyexists was removed in Django 1.4.

Model

from django.db import models

class Suggestion(models.Model):
    title = models.CharField(maxlength=100)
    email = models.EmailField(blank=True)
    link = models.URLField(verify_exists=True,blank=True)
    description = models.TextField(blank=True)
    time_sensitive = models.BooleanField()
    approved = models.BooleanField()

    def __unicode(self):
        return self.title

Form

from django import forms
from django.forms import ModelForm
from contact.models import Suggestion

class SuggestionForm(ModelForm):
    class Meta:
        model = Suggestion
        exclude = ('approved',)

View

from django.shortcuts import 
from django.template import RequestContext

from contact.forms import 

def suggestion(request):
    if request.method == "POST":

        form = SuggestionForm(request.POST)

        if(form.is_valid()):
            print(request.POST['title'])
            message = 'success'
        else:
            message = 'fail'

        return render_to_response('contact/suggestion.html',
              {'message': message},
              context_instance=RequestContext(request))
    else:
        return render_to_response('contact/suggestion.html',
                {'form': SuggestionForm()},
                context_instance=RequestContext(request))

Template

{% extends "base.html" %}

{% block content %}
<h1>Leave a Suggestion Here</h2>
{% if message %}
{{ message }}
{% endif %}
<div>
    <form action="/suggestion/" method="post">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit Feedback" />
    </form>
</div>
{% endblock %}

comments powered by Disqus