Forms Part 2: Class Based Forms

Forms are generally annoying to deal with. Fortunately Django offers some great ways to work with forms to make your life easier. In this our second part on forms we walk you through Class Based Forms in Django on our way to understanding the breadth of what you can do with forms in Django.

forms.py

from django import forms

class FeedbackForm(forms.Form):
    email = forms.EmailField(label="Your Email")
    name = forms.CharField(label="Name")
    message = forms.CharField(label="Body",widget=forms.Textarea)

views.py

from contact.forms import *

def contact(request):
    if request.method == "POST":
        form = FeedbackForm(request.POST)

        if(form.is_valid()):
            print(request.POST['name'])
            print(request.POST['message'])
            message = "thank you for your feedback"
        else:
            message = "sorry something went wrong"
        return render_to_response('contact/contact.html',
                {'success': message},
                context_instance=RequestContext(request))
    else:
        return render_to_response('contact/contact.html',
                {'form':FeedbackForm()},
                context_instance=RequestContext(request))

Template

<form action="/contact/" method="post">{% csrf_token %}
  {% for field in form %}
  <div>{{ field.label_tag }} {{ field }}</div>
  {% endfor %}
  <input type="submit" value="Submit Feedback" />
</form>

comments powered by Disqus