DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Using Django to Validate International Postcodes

Using Django to Validate International Postcodes

David Winterbottom user avatar by
David Winterbottom
·
Mar. 17, 12 · Interview
Like (0)
Save
Tweet
Share
5.12K Views

Join the DZone community and get the full member experience.

Join For Free

Problem

You want to validate a post/zip-code when you only know the country at runtime.

Solution

Use this snippet to dynamically fetch a validation method from Django's suite of "localflavor" form fields using the ISO 3166-1 two character country code.

def get_postcode_validator(country_code):
    # Django 1.3 uses 'UK' instead of GB - this changes in 1.4
    if country_code == 'GB':
        country_code = 'UK'
    module_path = 'django.contrib.localflavor.%s' % country_code.lower()
    try:
        module = __import__(module_path, fromlist=['forms'])
    except ImportError:
        # No forms module for this country
        return lambda x: x

    fieldname_variants = ['%sPostcodeField',
                          '%sPostCodeField',
                          '%sPostalCodeField',
                          '%sZipCodeField',]
    for variant in fieldname_variants:
        fieldname = variant % country_code.upper()
        if hasattr(module.forms, fieldname):
            return getattr(module.forms, fieldname)().clean
    return lambda x: x

As these validators are from forms, they will raise django.forms.ValidationError if the passed postcode is invalid. Hence your client code should look something like:

from django.forms import ValidationError

def is_postcode_valid(postcode, country_code):
    try:
        get_postcode_validator(country_code)(postcode)
    except ValidationError:
        return False
    return True

Discussion

As you can see, this is a touch messy as:

  • Django 1.3 uses the incorrect code for the UK (it should be 'GB')
  • There are a variety of different class names used for the appropriate field. We simply iterate over the possibilities and test to see if the class exists in the forms module.

This code is used within an internal Tangent geocoding webservice.

 

Django (web framework)

Published at DZone with permission of David Winterbottom, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 11 Observability Tools You Should Know
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Building a Real-Time App With Spring Boot, Cassandra, Pulsar, React, and Hilla
  • Spring Boot, Quarkus, or Micronaut?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: