Package of the week: LocalFlavor
Have you ever had to develop a web application with unique fields depending on the country to which the user is focused or to which the user belongs? The solution to these problem is a package called Django-localflavor, as the same documentation says: ‘’django-localflavor is a collection of assorted pieces of code that are useful for particular countries or cultures’’.
It is a very easy to use package that we have used in BeDjango with great results and we will try to explain it briefly
This package is really easy to install:
pip install django-localflavor
Then add ‘localflavor’ to your INSTALLED_APPS setting:
INSTALLED_APPS = ( # ... 'localflavor', )
Currently the package has specific fields for the following list of countries, although they accept new issues and PR in their repository in github
Some examples of these fields may be:
Spain: ESIdentityCardNumberField a form field that validates its input as a NIF/NIE/CIF code.
Switzerland: CHPhoneNumberField a form field that validate local Swiss phone number (not international ones).
Great Britain: GBCountySelect a Select widget that uses a list of UK Counties/Regions as its choices.
Adding one of these fields to our forms is as easy as importing the package we want:
from django import forms from localflavor.es.forms import ESIdentityCardNumberField class MyForm(forms.Form): spanish_identity_card = ESIdentityCardNumberField()
And this way we would have a form with a special field that will validate that the field spanish_identity_card is correct.
In addition to the unique country-by-country fields, this package contains some generic fields with utilities that can be useful to us without belonging to a particular country or culture such as IBAN bank account codes or dates.
An example of how to use these generic fields is as follows:
from django import forms from localflavor.generic.forms import IBANFormField class MyForm(forms.Form): iban = IBANFormField()