Forms
Forms
COMP 8347
Slides prepared by Dr. Arunita Jaekel
[email protected]
Django Forms
• Topics
– Django Forms
• The Form Class
• Fields and Widgets
– Rendering Forms
• Validating Forms
– ModelForm
2
Review MTV Architecture
• Model
– Represent data organization;
defines a table in a database.
• Template
– Contain information to be sent
to client; help generate final
HTML.
• View
– Actions performed by server
to generate data.
www.tikalk.com/files/intro-to-django.ppt
3
HTML Forms
4
GET and POST
5
GET and POST
6
Django’s Functionality
12
Building a Form
13
Building a Django Form
14
Field Arguments
– Field.required: By default, each Field class assumes the value is
required
• empty value raises a ValidationError exception
– Field.label: Specify the “human-friendly” label for this field.
name = forms.CharField(label='Your name')
– Field.initial: Specify initial value to use when rendering this Field in an
unbound Form.
name = forms.CharField(initial='John')
– Field.widget: Specify a Widget class to use when rendering this Field.
– Field.error_messages: Override the default messages that the field will
raise.
• Pass in a dictionary with keys matching the error messages you want
to override.
name = forms.CharField(error_messages={'required': 'Please enter your
name'})
…
ValidationError: [u'Please enter your name']
• The default error message is: [u'This field is required.']
16
Widgets
18
Create ContactForm Class
19
Instantiate and Render a Form
20
Bound and Unbound Forms
• A Form instance can be i) bound to a set of data, or ii) unbound.
– is_bound() method will tell you whether a form has data bound to it or not.
• An unbound form has no data associated with it.
– When rendered, it will be empty or contain default values.
– To create simply instantiate the class. e.g. f = NameForm()
• A bound form has submitted data,
• Can render the form as HTML with the data displayed in the HTML.
– To bind data to a form: Pass the data as a dictionary as the first parameter to
your Form class constructor
• The keys are the field names, correspond to the attributes in Form class.
• The values are the data you’re trying to validate.
data = {‘your_name’: ‘Arunita’}
form = NameForm (data)
or
form = ContactForm(request.POST)
21
The View
• Data sent back typically processed by same view which published the form
• If form is submitted using POST: populate it with data submitted
• If arrived at view with GET request: create an empty form instance;
from django.shortcuts import render
from django.http import HttpResponseRedirect
from myapp.forms import ContactForm
def contact(request):
if request.method == 'POST': # if POST process submitted data
22
A Sample Template
• Get your form into a template, using the context.
• return render(request, 'contact.html', {'myform': form})
• If the form is called 'myform' in the context, use {{myform}} in template.
• NOTE: This will not render the <form> tags or the submit button
• The form can be rendered manually or using one of the options:
• form.as_table, form.as_p or form.as_ul
• The form’s fields and their attributes will be unpacked into HTML
markup from the {{ myform }} form variable.
• The csrf_token template tag provides an easy-to-use protection
against Cross Site Request Forgeries
23
Rendering Options
• The name for each tag is from its attribute
from django import forms name.
class ContactForm(forms.Form): – The text label for each field is generated from
the field name by converting all underscores to
subject = spaces and upper-casing the first letter.
forms.CharField(max_length=100) Default suffix is ‘:’
message = – Example: cc_myself → ‘Cc myself:’
forms.CharField(widget=forms.Tex – These are defaults; you can also specify labels
tarea) manually.
sender = forms.EmailField() • Each text label is surrounded in an HTML
cc_myself = <label> tag, which points to a form field via
forms.BooleanField(required=Fals its id.
e) – Its id is generated by prepending 'id_' to the
field name.
• The id attributes and <label> tags are
included in the output by default.
– To change this, set auto_id=False
24
Rendering Forms
Output of {{myform.as_p}}
<form action="/myapp/contact/" method="post">
<p><label for="id_subject">Subject:</label>
from django import forms <input id="id_subject" type="text“ name="subject"
Class ContactForm(forms.Form): maxlength="100" /></p>
subject = <p><label for="id_message">Message:</label>
forms.CharField(max_length=1 <input type="text" name="message" id=
00) "id_message" /></p>
message = <p><label for="id_sender">Sender:</label>
forms.CharField(widget=forms. <input type="email" name="sender"
Textarea) id="id_sender"/></p>
sender = forms.EmailField() <p><label for="id_cc_myself">Cc myself:</label>
cc_myself = <input type="checkbox" name="cc_myself"
forms.BooleanField(required=F id="id_cc_myself" /></p>
alse) <input type="submit" value="Enter Contact Info" />
</form>
25
Form Validation
26
Validated Field Data
27
Form Validation – if Errors Found
28
Displaying Errors
• Rendering a bound Form object automatically runs the form’s validation
– HTML output includes validation errors as a <ul class="errorlist"> near the field.
– The particular positioning of the error messages depends on the output method.
>>> data = {'subject': ‘’, 'message': 'Hi there’, 'sender': ‘invalid email format’,
'cc_myself': True}
>>> f = ContactForm(data, auto_id=False)
>>> print(f.as_p ())
29
ModelForm
• ModelForm: a helper class to create a Form class from a Django Model.
–The generated Form class will have a form field for every model field
–the order specified in the fields attribute.
–Each model field has a corresponding default form field.
–Example: CharField on model → CharField on form.
– ForeignKey represented by ModelChoiceField: a ChoiceField whose choices
are a model QuerySet.
– ManyToManyField represented by ModelMultipleChoiceField: a
MultipleChoiceField whose choices are a model QuerySet.
– If the model field has blank=True, then required = False .
– The field’s label is set to the verbose_name of the model field, with the
first character capitalized.
– If the model field has choices set, then the form field’s widget will be set
to Select, with choices coming from the model field’s choices.
30
ModelForm Example
class Book(models.Model):
title = models.CharField(max_length=100)
length = models.IntegerField()
pub_date = models.DateField()
31
ModelForm Example
from django.db import models
PROV_CHOICES = ( (‘ON', ‘Ontario.'), (‘AB', from django.forms import
‘Alberta.'), (‘QC', ‘Quebec.'), ) ModelForm
class Author(models.Model): class AuthorForm(ModelForm):
name = class Meta:
models.CharField(max_length=100) model = Author
prov = models.CharField(max_length=3, fields = ['name', ‘prov',
choices=PROV_CHOICES) 'birth_date']
birth_date =
models.DateField(blank=True, null=True) class BookForm(ModelForm):
class Meta:
class Book(models.Model): model = Book
title = models.CharField(max_length=100) fields = [‘title', 'authors']
authors =models.ManyToManyField(Author)
32
Form vs ModelForm Examples
33
save() Method
34
ModelForm Validation
• Validation is triggered
– implicitly when calling is_valid() or accessing
the errors attribute
• Calling save() method can trigger validation, by
accessing errors attribute
– A ValueError is raised if form.errors is True.
35
Summary
• Django Forms
– The Form Class
– Fields and Widgets
• Rendering Forms
– Validating Forms
– Error messages
• ModelForm
– Saving and validating ModelForms
36
• [1] https://docs.djangoproject.com/en/3.0/topics/forms/
• [2] https://djangobook.com/django-tutorials/mastering-django-forms/
37