Django dynamic forms on the fly

Django is a really nice web framework for Python, and it definitely speeds up the development of web apps. In particular, Django makes it ridiculously easy to create web forms. It’s as simple as creating a new class with a few attributes:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

Any instance of ContactForm will have the methods the template engine needs to create nice looking forms automagically. In addition, it will have convenient methods for validation and cleaning data.

Django’s forms library is certainly convenient. In fact, it’s almost too convenient. There may be times when the paradigm seems a bit restrictive, and the workarounds seem to defeat the purpose of using Django’s forms library as a matter of convenience. For example, I found myself wanting a form with a variable number of fields depending on some previous input. This, in essence, is a dynamic form. Fortunately, someone had already tackled this problem as is often the case for problems I run across with Django. This elegant solution uses the type method in python to create a class that inherits forms.BaseForm and is assigned attributes via a dictionary argument. Here’s how I applied it to my madlib generator:

def make_edit_form(lib):
    fields = { 'phrase': forms.CharField(widget=forms.Textarea),}
    numBlanks = lib['numBlanks']
    for k in range(1,numBlanks+1):
        fields['blank'+str(k)] = forms.CharField(required=False)
    return type('EditLibForm',(forms.BaseForm,),{ 'base_fields': fields })

This dynamic form creates a field for each blank that exists in my madlib phrase. The output of this function is a class which thanks to the wonder of Python can be aliased and instanced:

EditLibForm = make_edit_form(current_madlib)
form = EditLibForm(request.POST)

It’s easy as pie, and I like pie. In particular, I like pecan and pumpkin pie which I will gladly accept as a donation towards this blog.

This entry was posted in computers, hacking and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>