SlideShare a Scribd company logo
Django Forms Best Practices, Tips and Tricks DjangoCon 2010 Shawn Rider PBS Education
Basic Forms from   django   import  forms  class   ContactForm (forms . Form):        subject  =  forms . CharField(max_length = 100 )        message  =  forms . CharField()        sender  =  forms . EmailField()        cc_myself  =  forms . BooleanField(required = False )        def  save (self):            data = self.cleaned_data            contact = Contact()            contact.subject = data.get('subject', '')            contact.message = data.get('message', '')             contact.sender = data.get('sender', '')             contact.cc_myself = data.get('cc_myself', False)             contact.save()            return contact
But that's so much to write...
Model Forms Easily create forms with just a few lines of code. Customize and modify fields available for editing on the form. Override default methods to support complex business logic, etc. Customized Model Forms can easily be used in Django Admin. Model Forms can be used with Model Formsets to edit multiple forms in a single view.
Model Forms from   django.forms   import  ModelForm  ### ... Form Definition ... ### class   ArticleForm (ModelForm):        class   Meta :            model  =  Article  ### ... Inside the View ... ### article = Article.objects.get(pk=article_id) if  request . method  ==   'POST' :        form  =  ArticleForm(request.POST, instance=article)        if  form.is_valid():           article = form.save()            return  HttpResponseRedirect(redirect_url)   else :        form = ArticleForm(instance=article)
Model Forms    A Model Form with listed editable fields and explicitly defined widgets: class   ArticleForm (ModelForm):       class   Meta :           model  =  Article           fields = ('title', 'content', 'blurb')          widgets = {              'content': Textarea(attrs:{'cols':80, 'rows':20})          } A Model Form with a custom save method: class   ArticleForm (ModelForm):       class   Meta :           model  =  Article      def   save( self, *args, **kwargs ) :           data  =  self.cleaned_data          ### Insert complex, custom save logic here. ###          return article
Formsets Formsets allow you to produce multiple forms for a page (bulk editing). Can be customized in many ways. Handle basic metadata to keep forms and data properly aligned. Formsets are used with basic Django forms. Model Formsets are used with Django Model Forms. Allow for validation of entire set of forms as well as individual forms within the formset.
Formsets ### View code ### def   manage_articles (request):        ArticleFormSet = formset_factory(ArticleForm)        if request.method == 'POST':           formset = ArticleFormSet(request.POST, request.FILES)            if formset.is_valid():                for form in formset:                    form.save()                return HttpResponseRedirect(REDIRECT_URL)      else:            formset = ArticleFormSet()        return render_to_response('manage_articles.html', {           'formset': formset       }) <!-- Template Code --> <form   method= &quot;post&quot;   action= &quot;&quot; >         <table>   {{   formset   }}   </table>   </form>
Dynamic Forms A Dynamic Form modulates the fields and/or choices available in the form Why would I ever need a Dynamic Form? Enforcing restricted permissions for different levels of user Providing choices based on user or system data (custom contact lists, for example) Enforcing other complex business logic
For some developers, it seems natural to use a &quot;code factory&quot; design pattern to solve this problem. Please don't do that.
Override __init__ function class   ContactForm (forms.Form):       def __init__(self, user, *args, **kwargs):           super(ContactForm, self).__init__(*args, **kwargs)           if not user.is_authenticated():               self.fields['captcha'] = CaptchaField()      name = forms.CharField(max_length=50)      email = forms.Emailfield()      message = forms.CharField(widget=forms.Textarea) Code Factory def  make_contact_form (user):       # The basic form       class _ContactForm (forms.Form):          name = forms.CharField(max_length=50)          email = forms.EmailField()          message = forms.CharField(widget=forms.Textarea)              if user.is_authenticated():         return _ContactForm       class _CaptchaContactForm (_ContactForm):         captcha = CaptchaField()                       return _CaptchaContactForm  (Taken from James Bennett's http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/)
Dynamic Forms class   MemberSearchForm ( forms . Form ):      def  __init__ ( self ,  data = None ,  account = None ,   * args ,   ** kwargs ):          self . account  =  account          super ( MemberSearchForm ,  self ). __init__ ( data ,   * args ,   ** kwargs )      terms  =  forms . CharField ( required = False )      role  =  forms . ChoiceField ( choices = SEARCH_ROLE_CHOICES ,  required = False )      status  =  forms . ChoiceField ( choices = SEARCH_STATUS_CHOICES ,  required = False )
Tip:  Always Redirect After Modifying Data article = Article.objects.get(pk=article_id)   if  request . method  ==   'POST' :       form  =  ArticleForm(request.POST, instance=article)        if  form.is_valid():           article = form.save()            return HttpResponseRedirect(redirect_url)    else :        form = ArticleForm(instance=article)
The Worst Example in the Django docs? def   contact (request):        if  request . method  ==   'POST' :  # If the form has been submitted...           form  =  ContactForm(request . POST)  # A form bound to the POST data           if  form . is_valid():  # All validation rules pass            subject  =  form . cleaned_data[ 'subject' ]            message  =  form . cleaned_data[ 'message' ]            sender  =  form . cleaned_data[ 'sender' ]            cc_myself  =  form . cleaned_data[ 'cc_myself' ]            recipients  =  [ 'info@example.com' ]            if  cc_myself:                recipients . append(sender)                from   django.core.mail   import  send_mail                send_mail(subject, message, sender, recipients)            return  HttpResponseRedirect( '/thanks/' )  # Redirect after POST        else :            form  =  ContactForm()  # An unbound form        return  render_to_response( 'contact.html' , {  'form' : form, })
Tip: Use Forms to Isolate Logic class   MemberSearchForm ( forms . Form ):       def  __init__ ( self ,  data = None ,  account = None ,   * args ,   ** kwargs ):           self . account  =  account           super ( MemberSearchForm ,  self ). __init__ ( data ,   * args ,   ** kwargs )      terms  =  forms . CharField ( required = False )       role  =  forms . ChoiceField ( choices = SEARCH_ROLE_CHOICES ,  required = False )       status  =  forms . ChoiceField ( choices = SEARCH_STATUS_CHOICES ,  required = False )        def  search ( self ):          data  =  self . cleaned_data           ### Complex Search Logic Here ###          return results
Tip: Use django-uni-form
Tip: Roll Your Own Fields and Form Classes Isolate logic at any cost Sometimes objects or features in your project warrant a completely custom Form Field Custom Form Classes can perform custom templatized output, eliminating repetitive HTML in your templates Sub Tip: Extend existing classes to save yourself headaches
Thanks and Further Reading James Bennett's B-List: http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ Danny Greenfield’s Django-Uniform: http://github.com/pydanny/django-uni-form/

More Related Content

What's hot (20)

PDF
Django in Production
Hyun-woo Park
 
PPTX
Basic Python Django
Kaleem Ullah Mangrio
 
PDF
Introduction to Django REST Framework, an easy way to build REST framework in...
Zhe Li
 
ODP
Django for Beginners
Jason Davies
 
PDF
A Basic Django Introduction
Ganga Ram
 
PDF
Quick flask an intro to flask
juzten
 
PDF
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
PDF
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
 
PPTX
OCP Java (OCPJP) 8 Exam Quick Reference Card
Hari kiran G
 
KEY
Introduction Django
Wade Austin
 
PPTX
Introduction to PHP
Collaboration Technologies
 
PDF
Introduction to django
Ilian Iliev
 
PPT
Class 3 - PHP Functions
Ahmed Swilam
 
PDF
Xe 구조에 대한 이해
Dong Hyun Kim
 
PPT
Oops concepts in php
CPD INDIA
 
PDF
Cours php & Mysql - 2éme partie
kadzaki
 
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
PDF
Basic Crud In Django
mcantelon
 
PPTX
Introducción a HTML5 y CSS3
Paradigma Digital
 
PPTX
Loops PHP 04
mohamedsaad24
 
Django in Production
Hyun-woo Park
 
Basic Python Django
Kaleem Ullah Mangrio
 
Introduction to Django REST Framework, an easy way to build REST framework in...
Zhe Li
 
Django for Beginners
Jason Davies
 
A Basic Django Introduction
Ganga Ram
 
Quick flask an intro to flask
juzten
 
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
Hari kiran G
 
Introduction Django
Wade Austin
 
Introduction to PHP
Collaboration Technologies
 
Introduction to django
Ilian Iliev
 
Class 3 - PHP Functions
Ahmed Swilam
 
Xe 구조에 대한 이해
Dong Hyun Kim
 
Oops concepts in php
CPD INDIA
 
Cours php & Mysql - 2éme partie
kadzaki
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Basic Crud In Django
mcantelon
 
Introducción a HTML5 y CSS3
Paradigma Digital
 
Loops PHP 04
mohamedsaad24
 

Similar to Django Forms: Best Practices, Tips, Tricks (20)

PDF
The Django Book - Chapter 7 forms
Vincent Chien
 
PDF
Forms, Getting Your Money's Worth
Alex Gaynor
 
PDF
Autoforms
jeff kit
 
PDF
djangoic approach to implement common web development paradigms
Lakshman Prasad
 
PDF
Web Development Paradigms and djangoic approach to deal with them
Lakshman Prasad
 
PPTX
CHAPTER_4_DJANGO_FORMS[1] [Read-Only].pptx
bestboybulshaawi
 
PPTX
chapter Two Django basics of dynamic web pages.pptx
bestboybulshaawi
 
PPTX
Custom Signals for Uncoupled Design
ecomsmith
 
PDF
Two Scoops of Django - Common Patterns for Forms
Vic Yang
 
KEY
Setting a baseline for your django projects
Gary Reynolds
 
PPTX
django Forms in a Web API World
Tareque Hossain
 
PPTX
Django crush course
Mohammed El Rafie Tarabay
 
PDF
Five class-based views everyone has written by now
James Aylett
 
PDF
Django Bogotá. CBV
ctrl-alt-delete
 
PDF
What’S New In Newforms Admin
DjangoCon2008
 
PDF
Django Good Practices
Solution4Future
 
PDF
Django Heresies
Simon Willison
 
PDF
Introduction to Django
Joaquim Rocha
 
PPTX
Tango with django
Rajan Kumar Upadhyay
 
PDF
Action View Form Helpers - 1, Season 2
RORLAB
 
The Django Book - Chapter 7 forms
Vincent Chien
 
Forms, Getting Your Money's Worth
Alex Gaynor
 
Autoforms
jeff kit
 
djangoic approach to implement common web development paradigms
Lakshman Prasad
 
Web Development Paradigms and djangoic approach to deal with them
Lakshman Prasad
 
CHAPTER_4_DJANGO_FORMS[1] [Read-Only].pptx
bestboybulshaawi
 
chapter Two Django basics of dynamic web pages.pptx
bestboybulshaawi
 
Custom Signals for Uncoupled Design
ecomsmith
 
Two Scoops of Django - Common Patterns for Forms
Vic Yang
 
Setting a baseline for your django projects
Gary Reynolds
 
django Forms in a Web API World
Tareque Hossain
 
Django crush course
Mohammed El Rafie Tarabay
 
Five class-based views everyone has written by now
James Aylett
 
Django Bogotá. CBV
ctrl-alt-delete
 
What’S New In Newforms Admin
DjangoCon2008
 
Django Good Practices
Solution4Future
 
Django Heresies
Simon Willison
 
Introduction to Django
Joaquim Rocha
 
Tango with django
Rajan Kumar Upadhyay
 
Action View Form Helpers - 1, Season 2
RORLAB
 
Ad

More from Shawn Rider (8)

PDF
Work is not a Dare: Tips for Building Inclusive Teams
Shawn Rider
 
PDF
Theming Sites with SASS
Shawn Rider
 
PPTX
Living Syleguides
Shawn Rider
 
PDF
Intro to Yo
Shawn Rider
 
PPTX
Barbarians at the Gate: Games and Culture
Shawn Rider
 
PPTX
Massaging the Pony: Message Queues and You
Shawn Rider
 
PPT
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django Site
Shawn Rider
 
PPTX
How To Succeed In Web Design
Shawn Rider
 
Work is not a Dare: Tips for Building Inclusive Teams
Shawn Rider
 
Theming Sites with SASS
Shawn Rider
 
Living Syleguides
Shawn Rider
 
Intro to Yo
Shawn Rider
 
Barbarians at the Gate: Games and Culture
Shawn Rider
 
Massaging the Pony: Message Queues and You
Shawn Rider
 
Teaching an Old Pony New Tricks: Maintaining and Updating and Aging Django Site
Shawn Rider
 
How To Succeed In Web Design
Shawn Rider
 
Ad

Recently uploaded (20)

PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Digital Circuits, important subject in CS
contactparinay1
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 

Django Forms: Best Practices, Tips, Tricks

  • 1. Django Forms Best Practices, Tips and Tricks DjangoCon 2010 Shawn Rider PBS Education
  • 2. Basic Forms from django import forms  class ContactForm (forms . Form):       subject = forms . CharField(max_length = 100 )       message = forms . CharField()       sender = forms . EmailField()       cc_myself = forms . BooleanField(required = False )       def save (self):           data = self.cleaned_data           contact = Contact()           contact.subject = data.get('subject', '')           contact.message = data.get('message', '')           contact.sender = data.get('sender', '')           contact.cc_myself = data.get('cc_myself', False)           contact.save()           return contact
  • 3. But that's so much to write...
  • 4. Model Forms Easily create forms with just a few lines of code. Customize and modify fields available for editing on the form. Override default methods to support complex business logic, etc. Customized Model Forms can easily be used in Django Admin. Model Forms can be used with Model Formsets to edit multiple forms in a single view.
  • 5. Model Forms from django.forms import ModelForm  ### ... Form Definition ... ### class ArticleForm (ModelForm):       class Meta :           model = Article ### ... Inside the View ... ### article = Article.objects.get(pk=article_id) if request . method == 'POST' :       form = ArticleForm(request.POST, instance=article)       if form.is_valid():          article = form.save()           return HttpResponseRedirect(redirect_url)   else :       form = ArticleForm(instance=article)
  • 6. Model Forms    A Model Form with listed editable fields and explicitly defined widgets: class   ArticleForm (ModelForm):       class   Meta :           model  =  Article           fields = ('title', 'content', 'blurb')          widgets = {              'content': Textarea(attrs:{'cols':80, 'rows':20})          } A Model Form with a custom save method: class   ArticleForm (ModelForm):       class   Meta :           model  =  Article      def   save( self, *args, **kwargs ) :           data  =  self.cleaned_data          ### Insert complex, custom save logic here. ###          return article
  • 7. Formsets Formsets allow you to produce multiple forms for a page (bulk editing). Can be customized in many ways. Handle basic metadata to keep forms and data properly aligned. Formsets are used with basic Django forms. Model Formsets are used with Django Model Forms. Allow for validation of entire set of forms as well as individual forms within the formset.
  • 8. Formsets ### View code ### def manage_articles (request):       ArticleFormSet = formset_factory(ArticleForm)       if request.method == 'POST':          formset = ArticleFormSet(request.POST, request.FILES)           if formset.is_valid():               for form in formset:                   form.save()               return HttpResponseRedirect(REDIRECT_URL)     else:           formset = ArticleFormSet()       return render_to_response('manage_articles.html', {          'formset': formset      }) <!-- Template Code --> <form method= &quot;post&quot; action= &quot;&quot; >        <table> {{ formset }} </table>   </form>
  • 9. Dynamic Forms A Dynamic Form modulates the fields and/or choices available in the form Why would I ever need a Dynamic Form? Enforcing restricted permissions for different levels of user Providing choices based on user or system data (custom contact lists, for example) Enforcing other complex business logic
  • 10. For some developers, it seems natural to use a &quot;code factory&quot; design pattern to solve this problem. Please don't do that.
  • 11. Override __init__ function class ContactForm (forms.Form):       def __init__(self, user, *args, **kwargs):           super(ContactForm, self).__init__(*args, **kwargs)           if not user.is_authenticated():               self.fields['captcha'] = CaptchaField()      name = forms.CharField(max_length=50)      email = forms.Emailfield()      message = forms.CharField(widget=forms.Textarea) Code Factory def make_contact_form (user):       # The basic form       class _ContactForm (forms.Form):         name = forms.CharField(max_length=50)         email = forms.EmailField()         message = forms.CharField(widget=forms.Textarea)              if user.is_authenticated():        return _ContactForm       class _CaptchaContactForm (_ContactForm):        captcha = CaptchaField()                       return _CaptchaContactForm  (Taken from James Bennett's http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/)
  • 12. Dynamic Forms class MemberSearchForm ( forms . Form ):     def __init__ ( self , data = None , account = None , * args , ** kwargs ):         self . account = account         super ( MemberSearchForm , self ). __init__ ( data , * args , ** kwargs )     terms = forms . CharField ( required = False )     role = forms . ChoiceField ( choices = SEARCH_ROLE_CHOICES , required = False )     status =  forms . ChoiceField ( choices = SEARCH_STATUS_CHOICES , required = False )
  • 13. Tip:  Always Redirect After Modifying Data article = Article.objects.get(pk=article_id) if request . method == 'POST' :      form = ArticleForm(request.POST, instance=article)       if form.is_valid():          article = form.save()           return HttpResponseRedirect(redirect_url)    else :       form = ArticleForm(instance=article)
  • 14. The Worst Example in the Django docs? def contact (request):       if request . method == 'POST' : # If the form has been submitted...          form = ContactForm(request . POST) # A form bound to the POST data          if form . is_valid(): # All validation rules pass           subject = form . cleaned_data[ 'subject' ]           message = form . cleaned_data[ 'message' ]           sender = form . cleaned_data[ 'sender' ]           cc_myself = form . cleaned_data[ 'cc_myself' ]           recipients = [ '[email protected]' ]           if cc_myself:               recipients . append(sender)               from django.core.mail import send_mail               send_mail(subject, message, sender, recipients)           return HttpResponseRedirect( '/thanks/' ) # Redirect after POST       else :           form = ContactForm() # An unbound form       return render_to_response( 'contact.html' , { 'form' : form, })
  • 15. Tip: Use Forms to Isolate Logic class MemberSearchForm ( forms . Form ):     def __init__ ( self , data = None , account = None , * args , ** kwargs ):         self . account = account         super ( MemberSearchForm , self ). __init__ ( data , * args , ** kwargs )     terms = forms . CharField ( required = False )     role = forms . ChoiceField ( choices = SEARCH_ROLE_CHOICES , required = False )     status = forms . ChoiceField ( choices = SEARCH_STATUS_CHOICES , required = False )     def search ( self ):         data = self . cleaned_data         ### Complex Search Logic Here ###          return results
  • 17. Tip: Roll Your Own Fields and Form Classes Isolate logic at any cost Sometimes objects or features in your project warrant a completely custom Form Field Custom Form Classes can perform custom templatized output, eliminating repetitive HTML in your templates Sub Tip: Extend existing classes to save yourself headaches
  • 18. Thanks and Further Reading James Bennett's B-List: http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ Danny Greenfield’s Django-Uniform: http://github.com/pydanny/django-uni-form/

Editor's Notes

  • #3: This is a plain vanilla form built in Django. It allows a website user to &amp;quot;contact&amp;quot; the website; hence, the name. Forms are used for data entry and modification. Django gives developers many handy tools to simplify working with forms. But many Django devs are still afraid to write and work with forms, and they lean on the Django Admin perhaps too much.
  • #4: Add LOLcat image that sez halp!
  • #6: Here is what a Model Form implementation looks like in practice.
  • #7: Here are some examples of how you can override or add to a Model Form.  Django provides several ways to easily customize a Model Form, including the fields attribute, the exclude attribute, and the widgets attribute.
  • #9: Note that the formset defaults to a table-based output. This can be modified by manually looping through the formset in the template and outputting using any of the default Django formats. TIP: Formsets do write in a &amp;quot;management&amp;quot; form in your template. If you are doing any fancy JS stuff, you might need to manipulate this management form.
  • #11: Factories are common design patterns in many languages. Factories can and do work in Python and in Django forms.
  • #12: The form on top is a snippet of a form made dynamic by overriding the __init__ function. For most types of form customization, this is the preferred way of handling dynamic forms. The example on bottom shows what a factory version of the same form would look like. 
  • #13: This example of a dynamic form shows a solution to another common problem. The goal is to have additional data available for validating some part of the submitted data. (In this case, for limiting results of the search that is being performed.) This technique is also very handy for generating choice tuples based on custom queries.
  • #15: Always try to isolate logic in places that is reusable. Forms are good places to keep reusable code elements, and the form.save() method is one of the most valuable.
  • #16: By isolating functionality like this, it becomes possible to easily adapt to other system structures. For example, adding Message Queues to functions is very easy if you properly abstract code away from your Views.