django-angular Documentation, Release 2.2
2.7 Tutorial: Django Forms with AngularJS
Django offers an excellent Form framework which is responsible for rendering and validating HTML forms. Since
Django’s design philosophy is to be independent of the styling and JavaScript, this Form framework requires some
adoption in order to play well with AngularJS and optionally Bootstrap.
A common technique to adopt the styling of a Django Form, is to extend the template so that each Form field is
rendered by hand written HTML. This of course leads to code duplication and is a violation of the DRY principle.
An alternative technique is to add crispy-forms to your project and enrich the Django Forms with a helper class.
Unfortunately, crispy-form does not work very well with django-angular. In order to add the same functionality in a
“DRY” manner, a special Mixin class can be added to your forms, rather than having to work with helper-classes.
This tutorial attempts to explain how to combine the Django Form framework in combination with AngularJS and
Bootstrap.
2.7.1 Basic Form Submission
Lets start with a very basic example, a functioning demo is available here: http://django-angular.awesto.com/classic_
form/
Say, we have a simple but rather long Form definition, to subscribe a person wanting to visit us:
1 from __future__ import unicode_literals
2 from djng.forms import fields
3 class SubscribeForm(Bootstrap3Form):
4 use_required_attribute = False
5
6 CONTINENT_CHOICES = [('am', 'America'), ('eu', 'Europe'), ('as', 'Asia'), ('af',
˓→'Africa'),
7 ('au', 'Australia'), ('oc', 'Oceania'), ('an', 'Antartica')]
8 TRAVELLING_BY = [('foot', 'Foot'), ('bike', 'Bike'), ('mc', 'Motorcycle'), ('car',
˓→ 'Car'),
9 ('public', 'Public Transportation'), ('train', 'Train'), ('air',
˓→'Airplane')]
10 NOTIFY_BY = [('email', 'EMail'), ('phone', 'Phone'), ('sms', 'SMS'), ('postal',
˓→'Postcard')]
11
12 first_name = fields.CharField(
13 label='First name',
14 min_length=3,
15 max_length=20)
16
17 last_name = fields.RegexField(
18 r'^[A-Z][a-z -]?',
19 label='Last name',
20 error_messages={'invalid': 'Last names shall start in upper case'})
21
22 sex = fields.ChoiceField(
23 choices=(('m', 'Male'), ('f', 'Female')),
24 widget=widgets.RadioSelect,
25 error_messages={'invalid_choice': 'Please select your sex'})
26
27 email = fields.EmailField(
28 label='E-Mail',
29 required=True,
30 help_text='Please enter a valid email address')
(continues on next page)
2.7. Tutorial: Django Forms with AngularJS 19