django_forms_cheat.txtPage 1 of 2 Aug/2008
1# Simple Form with standard widgets.2
from
django
import
forms3
class
ContactForm(forms.Form):
4 subject=forms.CharField(max_length=100)
5 message=forms.CharField()
6 sender=forms.EmailField()
7 cc_myself=forms.BooleanField(required=
False
) # required=True by default89# Form with non-standard widget used10
class
CommentForm(forms.Form):
11 name=forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
12 url=forms.URLField()
13 comment=forms.CharField(widget=forms.TextInput(attrs={'size':'40'}))
1415# Using forms16 f=ContactForm() # unbound - no data
17 data= {'subject': 'hello',
18'message': 'Hi there',
19'sender': 'foo@example.com',
20'cc_myself':
True
,21'extra_field': 'foo'}
22 f=ContactForm(data) # bound - has data
23 f.is_valid() # validate
24 f.cleaned_data# returns a dictionary of the data - note: extra_field is dropped
2526# outputting html data all outputs automatically give labelled ids27 f.as_p() # renders as paragraphs
28 f.as_ul() # renders as dot-points (no <ul>)
29 f.as_table()
3031# Mapping forms to models32
class
BlogForm(forms.ModelForm):
33# name = CharField(widget=forms.TextInput()) # you can override any field if you wish34
class
Meta:35 model=Blog# where Article is something that inherits model.Model
36 fields= ('name',) # 'fields' specifies visible fields - so can't edit tagline, etc
37# exclude = ('tagline', 'bestEntry') # this also works, chose 'fields' or 'exclude'3839 form1=BlogForm() # just like a normal form. all normal form methods available
40 myblog=Blog.objects.get(id=1)
41 form2=BlogForm(instance=myblog) # just like normal binding
42 form2.save() # generate a model, then inserts it into db, or updates db
43# creating a new blog via a form44 b=Blog()
45 form3=BlogForm(request.POST,instance=b)
46 new_blog=form3.save(commit=
False
) # generates a model, but doesn't insert into db47 new_blog.tagline= ... # since the form excluded this field, it must be filled before savin
g48 new_blog.save() # saves the generated model
49 f.save_m2m() # saves many-to-many data - this is required only if you have commit=False
5051# Sample use of forms:52
def
contact(request):
53
if
request.method== 'POST':
54 form=ContactForm(request.POST,request.FILES)
55# the second parameter is optional56
if
form.is_valid():
57# Do form processing here...58
return
HttpResponseR