Django Localflavor Example

Introduction

Today i’ve created Polish version of the localflavor module. It consist of some fields created with Polish special content. After a few days i’ll commit this patch to the Trac ticket system. Nowadays it can be found here.

There’s no obvious example of creating forms with the localflavor module. Very little is inside newforms documentation, but not so much and in hidden way. This example provides project using localflavor forms.

Scope

Create an example form with all of Polish custom fields, validate the entered data and when everything is fine render a success page.

Creating Form

I’ve to compress some of the text in order to correctly display on this web page.

We’re creating a standard form with all fields. Important for Select fields is that they’re not created with the SelectField but with the CharField with a widget set to desired data provider (eg. PLVoivodeshipSelect)

# example of definiton for all possible fields from
# Polish localflavor

from django import newforms as forms
from django.contrib.localflavor.pl.forms import *

class LocalForm(forms.Form):
woivodeship=forms.CharField(widget=PLVoivodeshipSelect())
administrative_unit=forms.CharField(widget=PLAdministrativeUnitSelect())
postal_code=PLPostalCodeField()
tax_number=PLTaxNumberField()
identification_number=PLNationalIdentificationNumberField()

Creating View

The view is just a simple view showing the form with a given template. With the POST method the form validates itself and when everything is fine it renders valid form page, otherwise it refreshes the form with the error messages.
from django.shortcuts import render_to_response
from forms import LocalForm

def localform(request):
“””
create or check example form
“””
if request.method == ‘POST’:
form = LocalForm(request.POST)
if form.is_valid():
return render_to_response(‘formvalid.html’,”)
else:
form = LocalForm()

return render_to_response(‘localform.html’, {‘form’: form})

Files

Example project with all of the above examples: