Creating custom fields using Django’s newforms Framework


I simply adore Django’s newforms framework. Creating HTML forms and processing them, both of which, as any web developer would love to tell you with a grimace on their face, are extremely tedious and monotonous tasks, have never been easier with Django.

Part of the reason I like it is that each field in the form can be easily customised further. Take an example of a field in a form I created that accepts a picture. Instead of using one of the built-in fields provided by newforms, I extended newforms.Field, and created a custom PictureField which ensures the file specified has one of a couple of extensions. It raises a validation error otherwise, which automatically gets displayed on the page if the form object is first validated and then loaded into a template.

from django import newforms as forms

class PictureField(forms.Field):
  def clean(self, value):
    if not value:
      return
    file_exts = ('.png', '.jpg', '.jpeg', '.bmp',)
    from os.path import splitext
    if splitext(value)[1].lower() not in file_exts:
      raise forms.ValidationError("Only following Picture types accepted: %s"
      % ", ".join([f.strip('.') for f in file_exts]))
  return value

Within the form, I use it thusly:

class UserForm(forms.Form):
  picture = PictureField(label="Personal Picture", required=False, widget=forms.FileInput)

It is nothing fancy, really, but, at least to me, being Pythonic all the way, it puts the fun back in web development.

2 thoughts on “Creating custom fields using Django’s newforms Framework

  1. Pingback: Uploading files via newforms in Django made easy. « Libel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s