Here is a step-by-step recipe to start working with django-formrenderingtools.
In Python code, do as always: create a form class, use it in a view and pass it to a template as a template context variable.
In the examples below, we will use the following form class:
from django import forms
class ContactForm(forms.Form):
"""
A sample form, for use in test cases.
"""
subject = forms.CharField(
label='Subject',
max_length=100,
)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(
required=False,
help_text='Send a copy of the message to the sender.',
)
def clean(self):
"""This sample form never validates!"""
raise forms.ValidationError('Sorry, but this sample form never validates!')
This is a quite simple form. If you call is_valid(), then a “non field error” is always generated.
In the examples below, we suppose you use the form in a view that looks like the following:
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view(request):
if not request.method == 'POST':
form = ContactForm()
else:
form = ContactForm(request.POST)
template_data = {'my_form': form}
render_to_response('my_template.html',
template_data,
context_instance=RequestContext(request))
Do not forget to add the view in your URL conf.
You can test your view and template by rendering the form the old way.
Here is what you may used to write in my_template.html:
<form action="./" method="post">
{{ form.as_p }}
<input type="submit">
</form>
Here is the code required to start using django-formrenderingtools, so replace the previous template code by the following:
{% load form_layouts %}
<form action="./" method="post">
{% form form=my_form %}
<input type="submit">
</form>
Unfortunately this tutorial is not complete yet.
However, here are some additional notes: