100% found this document useful (7 votes)
9K views

Cheatsheet of Forms - Form For Django

This document provides information about Django forms, including how to create forms with standard and custom widgets, map forms to models, validate and process form data, and write custom forms and widgets. It lists common field and widget types in Django forms and common field arguments. It also includes an example of using a form to handle a basic contact form submission.

Uploaded by

windoze007
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (7 votes)
9K views

Cheatsheet of Forms - Form For Django

This document provides information about Django forms, including how to create forms with standard and custom widgets, map forms to models, validate and process form data, and write custom forms and widgets. It lists common field and widget types in Django forms and common field arguments. It also includes an example of using a form to handle a basic contact form submission.

Uploaded by

windoze007
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

django_forms_cheat.

txt
Page 1 of 2 Aug/2008
1 # Simple Form with standard widgets.
2 from django import forms
3 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 default
8
9 # Form with non-standard widget used
10 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'}))
14
15 # Using forms
16 f = ContactForm() # unbound - no data
17 data = {'subject': 'hello',
18 'message': 'Hi there',
19 'sender': '[email protected]',
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
25
26 # outputting html data all outputs automatically give labelled ids
27 f.as_p() # renders as paragraphs
28 f.as_ul() # renders as dot-points (no <ul>)
29 f.as_table()
30
31 # Mapping forms to models
32 class BlogForm(forms.ModelForm):
33 # name = CharField(widget=forms.TextInput()) # you can override any field if you wish
34 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'
38
39 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 form
44 b = Blog()
45 form3 = BlogForm(request.POST, instance=b)
46 new_blog = form3.save(commit=False) # generates a model, but doesn't insert into db
47 new_blog.tagline = ... # since the form excluded this field, it must be filled before savin
g
48 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
50
51 # 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 optional
56 if form.is_valid():
57 # Do form processing here...
58 return HttpResponseRedirect('/url/on_success/')
59 else:
60 form = ContactForm()
61 return render_to_response('contact.html', {'form': form})
62
63 # you can write your own forms if you really want to:
64 # see django_template_cheat.txt

- 1 -
django_forms_cheat.txt
Page 2 of 2 Aug/2008
65 <form method="post" action="">
66 <dl>
67 {% for field in form %}
68 <dt>{{ field.label_tag }}{% if field.field.required %}*{% endif %}</dt>
69 <dd>{{ field }}</dd>
70 {% if field.help_text %}<dd>{{ field.help_text }}</dd>{% endif %}
71 {% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>{% endif %}
72 {% endfor %}
73 </dl>
74 <input type="submit" />
75 </form>
76
77 # Writing custom widgets means supplying a render function
78 from django.template.loader import render_to_string
79 class CalendarWidget(forms.Widget):
80 def render(self, name, value, attrs=None):
81 return render_to_string("widget/CalendarWidget.html", locals())
82 class Media:
83 css = {'all': ('pretty.css',)}
84 js = ('animations.js', 'actions.js')
85
86 class BirthdayForm(forms.Form):
87 name = forms.CharField(max_length=100)
88 birthday = forms.DateField(widget=CalendarWidget)
89
90 # Field Type Reference
91 BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField,
92 EmailField, FileField, FilePathField, FloatField, ImageField, IntegerField,
93 IPAddressField, MultipleChoiceField, NullBooleanField, RegexField, TimeField,
94 URLField
95
96 # Field Argument Reference
97 required, label, initial, widget, help_text, error_messages
98
99 # Widget Type Reference
100 TextInput, PasswordInput, HiddenInput, FileInput, DateTimeInput, Textarea,
101 CheckboxInput, Select, SelectMultiple, RadioSelect, CheckboxSelectMultiple,
102 SplitDateTimeWidget
103

- 2 -

You might also like