1. Matthew Schinckel
  2. django-countries


django-countries / django_countries / views.py

import hashlib

from django.http import HttpResponse
from django.views.decorators.http import etag
from django.core.urlresolvers import reverse
from django.utils import simplejson
from django.shortcuts import render

from countries import COUNTRIES, COUNTRY_CODES
from fields import Country
from widgets import DynamicProvincesWidget

@etag(lambda x: hashlib.md5(str(COUNTRIES)).hexdigest())
def countries(request):
    if 'name' in request.GET:
        # Return a country widget with the given name.
    data = [{
        "links": [
            {"rel": "provinces", "uri": reverse('provinces', args=(code.lower(),))},
            {"rel": "validate_mobile_number", "uri": reverse("validate_mobile", args=(code.lower(),))},
    } for code,name in COUNTRIES]
    return HttpResponse(simplejson.dumps(data))

@etag(lambda x,y: hashlib.md5(str(Country(y.upper()))).hexdigest())
def provinces(request, code):
    country = Country(code.upper())
    if not country.name:
        return HttpResponse("Unable to find country with code %s" % code.upper(), status=404)
    if 'name' in request.GET:
        return HttpResponse(
                name=request.GET.get('name', ''),
                value=request.GET.get('value', ''),
                    'data-country-field': request.GET.get('country-field', ''),

    if country.provinces:        
        return HttpResponse(simplejson.dumps(country.provinces, default=unicode))
        return HttpResponse("No provinces found for %s" % country, status=404)

def validate_mobile(request, country_code):
    country = Country(country_code.upper())
    number = request.REQUEST.get('number', '')
    if not country.name:
        return HttpResponse("Unable to find country with code %s" % country_code.upper(), status=404)
    return HttpResponse(simplejson.dumps({
        'number': number,
        'is_valid': country.validate_mobile(number) is not None