code
stringlengths
1
1.72M
language
stringclasses
1 value
from django.template import loader, RequestContext from django.http import Http404, HttpResponse from django.core.xheaders import populate_xheaders from django.core.paginator import Paginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist import warnings warnings.warn( 'Function-based generic v...
Python
import re from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import Http404 from django.utils.encoding import smart_str from django.utils.translation import ugettext as _ from django.views.generic.base import TemplateResponseMixin, View class SingleObjectMixin(object): "...
Python
from django.forms import models as model_forms from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponseRedirect from django.views.generic.base import TemplateResponseMixin, View from django.views.generic.detail import (SingleObjectMixin, SingleObjectTemplateRe...
Python
from django import http from django.core.exceptions import ImproperlyConfigured from django.template import RequestContext, loader from django.template.response import TemplateResponse from django.utils.functional import update_wrapper from django.utils.log import getLogger from django.utils.decorators import classonly...
Python
import datetime import time from django.template import loader, RequestContext from django.core.exceptions import ObjectDoesNotExist from django.core.xheaders import populate_xheaders from django.db.models.fields import DateTimeField from django.http import Http404, HttpResponse import warnings warnings.warn( 'Fu...
Python
from django.views.generic.base import View, TemplateView, RedirectView from django.views.generic.dates import (ArchiveIndexView, YearArchiveView, MonthArchiveView, WeekArchiveView, DayArchiveView, TodayArchiveView, DateDetailView) from django.vie...
Python
from django import http from django.views.decorators.csrf import requires_csrf_token from django.template import Context, RequestContext, loader # This can be called when CsrfViewMiddleware.process_view has not run, therefore # need @requires_csrf_token in case the template needs {% csrf_token %}. @requires_csrf_toke...
Python
import os import gettext as gettext_module from django import http from django.conf import settings from django.utils import importlib from django.utils.translation import check_for_language, activate, to_locale, get_language from django.utils.text import javascript_quote from django.utils.encoding import smart_unicod...
Python
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ from django.template import loader, RequestContext from django.http import HttpResponse, Http404 from django.http import HttpRespon...
Python
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from django.dispatch.dispatcher import Signal, receiver
Python
import weakref import threading from django.dispatch import saferef WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref) def _make_id(target): if hasattr(target, 'im_func'): return (id(target.im_self), id(target.im_func)) return id(target) class Signal(object): """ Base class ...
Python
""" "Safe weakrefs", originally from pyDispatcher. Provides a way to safely weakref any function, including bound methods (which aren't handled by the core weakref module). """ import weakref, traceback def safeRef(target, onDelete = None): """Return a *safe* weak reference to a callable target target -- th...
Python
""" Common checksum routines (used in multiple localflavor/ cases, for example). """ __all__ = ['luhn',] LUHN_ODD_LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) # sum_of_digits(index * 2) def luhn(candidate): """ Checks a candidate number for validity according to the Luhn algorithm (used in validation of, for ...
Python
"Commonly-used date structures" from django.utils.translation import ugettext_lazy as _, pgettext_lazy WEEKDAYS = { 0:_('Monday'), 1:_('Tuesday'), 2:_('Wednesday'), 3:_('Thursday'), 4:_('Friday'), 5:_('Saturday'), 6:_('Sunday') } WEEKDAYS_ABBR = { 0:_('Mon'), 1:_('Tue'), 2:_('Wed'), 3:_('Thu'), 4:_('Fri')...
Python
import imp import os import sys def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" name = ".".join([package.__name__, module_name]) try: # None indicates a cached miss; see mark_miss() in Python/import.c. return sys.modules[name] is not None except K...
Python
""" termcolors.py """ color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) background = dict([(color_names[x], '4%s' % x) for x in range(8)]) RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'rever...
Python
import types import urllib import locale import datetime import codecs from decimal import Decimal from django.utils.functional import Promise class DjangoUnicodeDecodeError(UnicodeDecodeError): def __init__(self, obj, *args): self.obj = obj UnicodeDecodeError.__init__(self, *args) def __str_...
Python
"""Thread-local objects (Note that this module provides a Python version of thread threading.local class. Depending on the version of Python you're using, there may be a faster one available. You should always import the local class from threading.) Thread-local objects support the management of thread-local dat...
Python
""" PHP date() style date formatting See http://www.php.net/date for format strings Usage: >>> import datetime >>> d = datetime.datetime.now() >>> df = DateFormat(d) >>> print df.format('jS F Y H:i') 7th October 2003 11:39 >>> """ import re import time import calendar from django.utils.dates import MONTHS, MONTHS_3, ...
Python
import datetime import time from django.utils.tzinfo import LocalTimezone from django.utils.translation import ungettext, ugettext def timesince(d, now=None): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, ...
Python
# Autoreloading launcher. # Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org). # Some taken from Ian Bicking's Paste (http://pythonpaste.org/). # # Portions copyright (c) 2004, CherryPy Team (team@cherrypy.org) # All rights reserved. # # Redistribution and use in source and binary forms, with ...
Python
import base64 import calendar import datetime import re import sys import urllib import urlparse from binascii import Error as BinasciiError from email.Utils import formatdate from django.utils.encoding import smart_str, force_unicode from django.utils.functional import allow_lazy ETAG_MATCH = re.compile(r'(?:W/)?"((...
Python
# License for code in this file that was taken from Python 2.5. # PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 # -------------------------------------------- # # 1. This LICENSE AGREEMENT is between the Python Software Foundation # ("PSF"), and the Individual or Organization ("Licensee") accessing and # otherwise usin...
Python
""" Utilities for XML generation/parsing. """ from xml.sax.saxutils import XMLGenerator class SimplerXMLGenerator(XMLGenerator): def addQuickElement(self, name, contents=None, attrs=None): "Convenience method for adding an element with no children" if attrs is None: attrs = {} self.startEl...
Python
# Performance note: I benchmarked this code using a set instead of # a list for the stopwords and was surprised to find that the list # performed /better/ than the set - maybe because it's only a small # list. stopwords = ''' i a an are as at be by for from how in is it of on or that the this to was what when where ''...
Python
import os import sys if os.name == 'posix': def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', umask=022): "Robustly turn into a UNIX daemon, running in our_home_dir." # First fork try: if os.fork() > 0: sys.exit(0...
Python
""" Functions for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe string" means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. '<') into the appropriate entities. """ f...
Python
import os import sys try: from functools import wraps except ImportError: # only needed for Python 2.4 def wraps(_): def _wraps(func): return func return _wraps __unittest = True def _relpath_nt(path, start=os.path.curdir): """Return a relative version of a path""" if...
Python
"""Unittest main program""" import sys import os import types from django.utils.unittest import loader, runner try: from django.utils.unittest.signals import installHandler except ImportError: installHandler = None __unittest = True FAILFAST = " -f, --failfast Stop on first failure\n" CATCHBREAK = ...
Python
import signal import weakref from django.utils.unittest.compatibility import wraps __unittest = True class _InterruptHandler(object): def __init__(self, default_handler): self.called = False self.default_handler = default_handler def __call__(self, signum, frame): installed_handler ...
Python
"""Test result object""" import sys import traceback import unittest from StringIO import StringIO from django.utils.unittest import util from django.utils.unittest.compatibility import wraps __unittest = True def failfast(method): @wraps(method) def inner(self, *args, **kw): if getattr(self, 'fail...
Python
import os import sys from django.utils.unittest.loader import defaultTestLoader def collector(): # import __main__ triggers code re-execution __main__ = sys.modules['__main__'] setupDir = os.path.abspath(os.path.dirname(__main__.__file__)) return defaultTestLoader.discover(setupDir)
Python
"""TestSuite""" import sys import unittest from django.utils.unittest import case, util __unittest = True class BaseTestSuite(unittest.TestSuite): """A simple test suite that doesn't provide class or module shared fixtures. """ def __init__(self, tests=()): self._tests = [] self.addTests...
Python
"""Test case implementation""" import sys import difflib import pprint import re import unittest import warnings from django.utils.unittest import result from django.utils.unittest.util import\ safe_repr, safe_str, strclass,\ unorderable_list_difference from django.utils.unittest.compatibility import wraps ...
Python
"""Various utility functions.""" __unittest = True _MAX_LENGTH = 80 def safe_repr(obj, short=False): try: result = repr(obj) except Exception: result = object.__repr__(obj) if not short or len(result) < _MAX_LENGTH: return result return result[:_MAX_LENGTH] + ' [truncated]...'...
Python
""" unittest2 unittest2 is a backport of the new features added to the unittest testing framework in Python 2.7. It is tested to run on Python 2.4 - 2.6. To use unittest2 instead of unittest simply replace ``import unittest`` with ``import unittest2``. Copyright (c) 1999-2003 Steve Purcell Copyright (c) 2003-2010 P...
Python
"""Main entry point""" import sys if sys.argv[0].endswith("__main__.py"): sys.argv[0] = "unittest2" __unittest = True from django.utils.unittest.main import main_ main_()
Python
"""Loading unittests.""" import os import re import sys import traceback import types import unittest from fnmatch import fnmatch from django.utils.unittest import case, suite try: from os.path import relpath except ImportError: from django.utils.unittest.compatibility import relpath __unittest = True de...
Python
"""Running tests""" import sys import time import unittest from django.utils.unittest import result try: from django.utils.unittest.signals import registerResult except ImportError: def registerResult(_): pass __unittest = True class _WritelnDecorator(object): """Used to decorate file-like obj...
Python
""" Synchronization primitives: - reader-writer lock (preference to writers) (Contributed to Django by eugene@lazutkin.com) """ try: import threading except ImportError: import dummy_threading as threading class RWLock: """ Classic implementation of reader-writer lock with preference to writers....
Python
"Implementation of tzinfo classes for use with datetime.datetime." import time from datetime import timedelta, tzinfo from django.utils.encoding import smart_unicode, smart_str, DEFAULT_LOCALE_ENCODING class FixedOffset(tzinfo): "Fixed offset in minutes east from UTC." def __init__(self, offset): if i...
Python
import decimal import datetime from django.conf import settings from django.utils.translation import get_language, to_locale, check_for_language from django.utils.importlib import import_module from django.utils.encoding import smart_str from django.utils import dateformat, numberformat, datetime_safe from django.util...
Python
""" Functions for reversing a regular expression (used in reverse URL resolving). Used internally by Django and not intended for external use. This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ # Mapping of an escape character to a r...
Python
import re from django.utils.encoding import force_unicode from django.utils.functional import allow_lazy from django.utils.translation import ugettext_lazy, ugettext as _ from htmlentitydefs import name2codepoint # Capitalizes the first letter of a string. capfirst = lambda x: x and force_unicode(x)[0].upper() + force...
Python
import os import stat from os.path import join, normcase, normpath, abspath, isabs, sep from django.utils.encoding import force_unicode # Define our own abspath function that can handle joining # unicode paths to a current working directory that has non-ASCII # characters in it. This isn't necessary on Windows since...
Python
import logging import sys from django.core import mail # Make sure a NullHandler is available # This was added in Python 2.7/3.2 try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Make sure that dictConfig is availabl...
Python
"""Implementation of JSONEncoder """ import re c_encode_basestring_ascii = None c_make_encoder = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', ...
Python
"""Implementation of JSONDecoder """ import re import sys import struct from django.utils.simplejson.scanner import make_scanner c_scanstring = None __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys...
Python
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of ...
Python
r"""Using simplejson from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -msimplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -msimplejson.tool Expecting property name: line 1 column 2 (char 2) """ from django.utils import simplejson def main(): i...
Python
"""JSON token scanner """ import re try: from simplejson._speedups import make_scanner as c_make_scanner except ImportError: c_make_scanner = None __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scan...
Python
""" A class for storing a tree graph. Primarily used for filter constructs in the ORM. """ from django.utils.copycompat import deepcopy class Node(object): """ A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other ...
Python
""" Providing iterator functions that are not in all version of Python we support. Where possible, we try to use the system-native version and only fall back to these implementations if necessary. """ import itertools # Fallback for Python 2.4, Python 2.5 def product(*args, **kwds): """ Taken from http://docs...
Python
import django import os.path import re def get_svn_revision(path=None): """ Returns the SVN revision in the form SVN-XXXX, where XXXX is the revision number. Returns SVN-unknown if anything goes wrong, such as an unexpected format of internal SVN files. If path is provided, it should be a dir...
Python
"Functions that help with dynamically creating decorators for views." try: from functools import wraps, update_wrapper, WRAPPER_ASSIGNMENTS except ImportError: from django.utils.functional import wraps, update_wrapper, WRAPPER_ASSIGNMENTS # Python 2.4 fallback. class classonlymethod(classmethod): def __g...
Python
from django.conf import settings from django.utils.safestring import mark_safe def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep=''): """ Gets a number (as a number or string), and returns it as a string, using formats definied as arguments: * decimal_sep: Decimal separator symbol...
Python
# This is a copy of the Python logging.config.dictconfig module, # reproduced with permission. It is provided here for backwards # compatibility for Python versions prior to 2.7. # # Copyright 2009-2010 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # docu...
Python
"""HTML utilities suitable for global use.""" import re import string from django.utils.safestring import SafeData, mark_safe from django.utils.encoding import force_unicode from django.utils.functional import allow_lazy from django.utils.http import urlquote # Configuration for urlize() function. LEADING_PUNCTUATIO...
Python
""" Django's standard crypto functions and utilities. """ import hmac from django.conf import settings from django.utils.hashcompat import sha_constructor, sha_hmac def salted_hmac(key_salt, value, secret=None): """ Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which...
Python
# Taken from Python 2.7 with permission from/by the original author. import sys def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in ...
Python
""" Fixes Python 2.4's failure to deepcopy unbound functions. """ import copy import types # Monkeypatch copy's deepcopy registry to handle functions correctly. if (hasattr(copy, '_deepcopy_dispatch') and types.FunctionType not in copy._deepcopy_dispatch): copy._deepcopy_dispatch[types.FunctionType] = copy._deepc...
Python
""" The md5 and sha modules are deprecated since Python 2.5, replaced by the hashlib module containing both hash algorithms. Here, we provide a common interface to the md5 and sha constructors, depending on system version. """ import sys if sys.version_info >= (2, 5): import hashlib md5_constructor = hashlib.m...
Python
from types import GeneratorType from django.utils.copycompat import copy, deepcopy class MergeDict(object): """ A simple class for creating new "virtual" dictionaries that actually look up values in more than one dictionary, passed in the constructor. If a key appears in more than one of the given d...
Python
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( ... title=u"Poynter E-Media Tidbits", ... link=u"http://www.poynter.org/column.asp?id=31", ... description=u"A group Weblog by the shar...
Python
# Python's datetime strftime doesn't handle dates before 1900. # These classes override date and datetime to support the formatting of a date # through its full "proleptic Gregorian" date range. # # Based on code submitted to comp.lang.python by Andrew Dalke # # >>> datetime_safe.date(1850, 8, 2).strftime("%Y/%m/%d was...
Python
"""Translation helper functions.""" import locale import os import re import sys import warnings import gettext as gettext_module from cStringIO import StringIO from threading import local from django.utils.importlib import import_module from django.utils.safestring import mark_safe, SafeData # Translations are cac...
Python
# These are versions of the functions in django.utils.translation.trans_real # that don't actually do anything. This is purely for performance, so that # settings.USE_I18N = False can use this module rather than trans_real.py. import warnings from django.conf import settings from django.utils.encoding import force_uni...
Python
""" Internationalization support. """ import warnings from os import path from django.utils.encoding import force_unicode from django.utils.functional import lazy from django.utils.importlib import import_module __all__ = ['gettext', 'gettext_noop', 'gettext_lazy', 'ngettext', 'ngettext_lazy', 'string_concat...
Python
""" This module contains helper functions for controlling caching. It does so by managing the "Vary" header of responses. It includes functions to patch the header of response objects directly and decorators that change functions to do that header-patching themselves. For information on the Vary header, see: http...
Python
from django.contrib.syndication import views from django.core.exceptions import ObjectDoesNotExist import warnings # This is part of the deprecated API from django.contrib.syndication.views import FeedDoesNotExist, add_domain class Feed(views.Feed): """Provided for backwards compatibility.""" def __init__(sel...
Python
from django.conf import settings from django.contrib.sites.models import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import HttpResponse, Http404 from django.template import loader, TemplateDoesNotExist, RequestContext from django.utils import feedgenera...
Python
""" Czech-specific form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Select, RegexField, Field from django.utils.translation import ugettext_lazy as _ import re birth_number = re.compile(r'^(?P<birth>\d{6})/?(?P<id>\d{3,4})$') ic_...
Python
""" Czech regions, translations get from http://www.crwflags.com/fotw/Flags/cz-re.html """ from django.utils.translation import ugettext_lazy as _ REGION_CHOICES = ( ('PR', _('Prague')), ('CE', _('Central Bohemian Region')), ('SO', _('South Bohemian Region')), ('PI', _('Pilsen Region')), ('CA', _(...
Python
""" India-specific Form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import gettext import re class INZipCodeField(RegexFiel...
Python
""" A mapping of state misspellings/abbreviations to normalized abbreviations, and an alphabetical list of states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ STATE_CHOICES = ( ('KA', 'Karnataka'), ('AP', 'Andhra Pr...
Python
""" NL-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode pc_re = re.compile('^\d{4}[A-Z]{2}$...
Python
from django.utils.translation import ugettext_lazy as _ PROVINCE_CHOICES = ( ('DR', _('Drenthe')), ('FL', _('Flevoland')), ('FR', _('Friesland')), ('GL', _('Gelderland')), ('GR', _('Groningen')), ('LB', _('Limburg')), ('NB', _('Noord-Brabant')), ('NH', _('Noord-Holland')), ('OV', _(...
Python
""" Iceland specific form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField from django.forms.widgets import Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode cla...
Python
# -*- coding: utf-8 -*- IS_POSTALCODES = ( ('101', u'101 Reykjavík'), ('103', u'103 Reykjavík'), ('104', u'104 Reykjavík'), ('105', u'105 Reykjavík'), ('107', u'107 Reykjavík'), ('108', u'108 Reykjavík'), ('109', u'109 Reykjavík'), ('110', u'110 Reykjavík'), ('111', u'111 Reykjavík'...
Python
# -*- coding: utf-8 -*- """ Swedish specific Form helpers """ import re from django import forms from django.utils.translation import ugettext_lazy as _ from django.core.validators import EMPTY_VALUES from django.contrib.localflavor.se.utils import (id_number_checksum, validate_id_birthday, format_personal_id_numbe...
Python
# -*- coding: utf-8 -*- """ An alphabetical list of Swedish counties, sorted by codes. http://en.wikipedia.org/wiki/Counties_of_Sweden This exists in this standalone file so that it's only imported into memory when explicitly needed. """ from django.utils.translation import ugettext_lazy as _ COUNTY_CHOICES = ( ...
Python
import re import datetime def id_number_checksum(gd): """ Calculates a Swedish ID number checksum, using the "Luhn"-algoritm """ n = s = 0 for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']): tmp = ((n % 2) and 1 or 2) * int(c) if tmp > 9: tmp = sum([int(...
Python
""" IT-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode from django.contrib.localflavor.it....
Python
# -*- coding: utf-8 -* REGION_CHOICES = ( ('ABR', 'Abruzzo'), ('BAS', 'Basilicata'), ('CAL', 'Calabria'), ('CAM', 'Campania'), ('EMR', 'Emilia-Romagna'), ('FVG', 'Friuli-Venezia Giulia'), ('LAZ', 'Lazio'), ('LIG', 'Liguria'), ('LOM', 'Lombardia'), ('MAR', 'Marche'), ('MOL', ...
Python
from django.utils.encoding import smart_str, smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': ...
Python
# -*- coding: utf-8 -* PROVINCE_CHOICES = ( ('AG', 'Agrigento'), ('AL', 'Alessandria'), ('AN', 'Ancona'), ('AO', 'Aosta'), ('AR', 'Arezzo'), ('AP', 'Ascoli Piceno'), ('AT', 'Asti'), ('AV', 'Avellino'), ('BA', 'Bari'), ('BT', 'Barletta-Andria-Trani'), # active starting from 2009 ...
Python
""" JP-specific Form helpers """ from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ from django.forms.fields import RegexField, Select class JPPostalCodeField(RegexField): """ A form field that validates its input is a Japanese postcode. Accepts 7 digits, wit...
Python
from django.utils.translation import ugettext_lazy JP_PREFECTURES = ( ('hokkaido', ugettext_lazy('Hokkaido'),), ('aomori', ugettext_lazy('Aomori'),), ('iwate', ugettext_lazy('Iwate'),), ('miyagi', ugettext_lazy('Miyagi'),), ('akita', ugettext_lazy('Akita'),), ('yamagata', ugettext_lazy('Yamagat...
Python
""" Chile specific form helpers. """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode class CLRegionSelect(Select): ""...
Python
# -*- coding: utf-8 -*- """ A list of Chilean regions as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ REGION_CHOICES = ( ('RM', u'Región Metropolitana de Santiago'), ('I', u'Región de Tarapacá'), ('II', u'Región de Ant...
Python
""" AT-specific Form helpers """ import re from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ re_ssn = re.compile(r'^\d{4} \d{6}') class ATZipCodeField(RegexField)...
Python
# -*- coding: utf-8 -* from django.utils.translation import ugettext_lazy as _ STATE_CHOICES = ( ('BL', _('Burgenland')), ('KA', _('Carinthia')), ('NO', _('Lower Austria')), ('OO', _('Upper Austria')), ('SA', _('Salzburg')), ('ST', _('Styria')), ('TI', _('Tyrol')), ('VO', _('Vorarlberg'...
Python
""" DE-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ import re id_re = re.compile(r"^(?P<residence>\d{10})(?P<origin>\w{1,3})[-\ ]?(?P<...
Python
# -*- coding: utf-8 -* from django.utils.translation import ugettext_lazy as _ STATE_CHOICES = ( ('BW', _('Baden-Wuerttemberg')), ('BY', _('Bavaria')), ('BE', _('Berlin')), ('BB', _('Brandenburg')), ('HB', _('Bremen')), ('HH', _('Hamburg')), ('HE', _('Hessen')), ('MV', _('Mecklenburg-We...
Python
""" Australian-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re PHONE_DIGITS_RE ...
Python
""" An alphabetical list of states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ STATE_CHOICES = ( ('ACT', 'Australian Capital Territory'), ('NSW', 'New South Wales'), ('NT', 'Northern Territory'), ('QLD', 'Q...
Python
""" PT-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.com...
Python
# -*- coding: utf-8 -*- """ AR-specific Form helpers. """ from django.forms import ValidationError from django.core.validators import EMPTY_VALUES from django.forms.fields import RegexField, CharField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ class...
Python
# -*- coding: utf-8 -*- """ A list of Argentinean provinces and autonomous cities as `choices` in a formfield. From http://www.argentina.gov.ar/argentina/portal/paginas.dhtml?pagina=425 This exists in this standalone file so that it's only imported into memory when explicitly needed. """ PROVINCE_CHOICES = ( ('B'...
Python
# -*- coding: utf-8 -*- """ BR-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, CharField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ ...
Python