Ticket #11251: au-models.2.diff

File au-models.2.diff, 8.5 KB (added by DrMeers, 5 years ago)

models, forms, tests and documentation

  • django/contrib/localflavor/au/models.py

     
     1from django.conf import settings
     2from django.utils.translation import ugettext_lazy as _
     3from django.db.models.fields import CharField
     4from django.contrib.localflavor.au.au_states import STATE_CHOICES
     5from django.contrib.localflavor.au import forms
     6
     7class AUStateField(CharField):
     8
     9    description = _("Australian State")
     10
     11    def __init__(self, *args, **kwargs):
     12        kwargs['choices'] = STATE_CHOICES
     13        kwargs['max_length'] = 3
     14        super(AUStateField, self).__init__(*args, **kwargs)
     15
     16
     17class AUPostCodeField(CharField):
     18
     19    description = _("Australian Postcode")
     20
     21    def __init__(self, *args, **kwargs):
     22        kwargs['max_length'] = 4
     23        super(AUPostCodeField, self).__init__(*args, **kwargs)
     24
     25    def formfield(self, **kwargs):
     26        defaults = {'form_class': forms.AUPostCodeField}
     27        defaults.update(kwargs)
     28        return super(AUPostCodeField, self).formfield(**defaults)
     29       
     30       
     31class AUPhoneNumberField(CharField):
     32
     33    description = _("Australian Phone number")
     34
     35    def __init__(self, *args, **kwargs):
     36        kwargs['max_length'] = 20
     37        super(AUPhoneNumberField, self).__init__(*args, **kwargs)
     38
     39    def formfield(self, **kwargs):
     40        defaults = {'form_class': forms.AUPhoneNumberField}
     41        defaults.update(kwargs)
     42        return super(AUPhoneNumberField, self).formfield(**defaults)
     43   
  • django/contrib/localflavor/au/forms.py

     
    1212PHONE_DIGITS_RE = re.compile(r'^(\d{10})$')
    1313
    1414class AUPostCodeField(RegexField):
    15     """Australian post code field."""
     15    """ Australian post code field.
     16
     17    Assumed to be 4 digits.
     18    Northern Territory 3-digit postcodes should have leading zero.
     19    """
    1620    default_error_messages = {
    17         'invalid': _('Enter a 4 digit post code.'),
     21        'invalid': _('Enter a 4 digit postcode.'),
    1822    }
    1923
    2024    def __init__(self, *args, **kwargs):
     25        if 'max_length' in kwargs:
     26            kwargs.pop('max_length')
    2127        super(AUPostCodeField, self).__init__(r'^\d{4}$',
    22             max_length=None, min_length=None, *args, **kwargs)
     28            max_length=4, min_length=None, *args, **kwargs)
    2329
     30       
    2431class AUPhoneNumberField(Field):
    2532    """Australian phone number field."""
    2633    default_error_messages = {
     
    4047            return u'%s' % phone_match.group(1)
    4148        raise ValidationError(self.error_messages['invalid'])
    4249
     50   
    4351class AUStateSelect(Select):
    4452    """
    4553    A Select widget that uses a list of Australian states/territories as its
  • tests/regressiontests/localflavor/tests.py

     
    11from django.test import TestCase
    22from models import Place
    3 from forms import PlaceForm
     3from forms import PlaceForm, AustralianPlaceForm
     4import re
    45
     6SELECTED_OPTION_PATTERN = r'<option value="%s" selected="selected">'
     7BLANK_OPTION_PATTERN = r'<option value="">'
     8INPUT_VALUE_PATTERN = r'<input[^>]*value="%s"[^>]*>'
     9
    510class USLocalflavorTests(TestCase):
    611    def setUp(self):
    712        self.form = PlaceForm({'state':'GA', 'state_req':'NC', 'name':'impossible'})
     
    8186<option value="WY">Wyoming</option>
    8287</select>"""
    8388        self.assertEqual(str(self.form['state']), state_select_html)
     89
     90       
     91class AULocalflavorTests(TestCase):
     92    def setUp(self):
     93        self.form = AustralianPlaceForm(
     94            {'state':'WA',
     95             'state_required':'QLD',
     96             'name':'dummy',
     97             'postcode':'1234',
     98             'postcode_required':'4321',
     99             })
     100       
     101    def test_get_display_methods(self):
     102        """ Ensure get_*_display() methods are added to model instances. """
     103        place = self.form.save()
     104        self.assertEqual(place.get_state_display(), 'Western Australia')
     105        self.assertEqual(place.get_state_required_display(), 'Queensland')
     106
     107    def test_default_values(self):
     108        """ Ensure that default values are selected in forms. """
     109        form = AustralianPlaceForm()
     110        self.assertTrue(re.search(SELECTED_OPTION_PATTERN % 'NSW',
     111                                  str(form['state_default'])))
     112        self.assertTrue(re.search(INPUT_VALUE_PATTERN % '2500',
     113                                  str(form['postcode_default'])))
     114       
     115    def test_required(self):
     116        """ Test that required AUStateFields throw appropriate errors. """
     117        form = AustralianPlaceForm({'state':'NSW', 'name':'Wollongong'})
     118        self.assertFalse(form.is_valid())
     119        self.assertEqual(
     120            form.errors['state_required'], [u'This field is required.'])
     121        self.assertEqual(
     122            form.errors['postcode_required'], [u'This field is required.'])       
     123   
     124    def test_field_blank_option(self):
     125        """ Test that the empty option is there. """
     126        self.assertTrue(re.search(BLANK_OPTION_PATTERN,
     127                                  str(self.form['state'])))
     128
     129    def test_selected_values(self):
     130        """ Ensure selected states match the initial values provided. """
     131        self.assertTrue(re.search(SELECTED_OPTION_PATTERN % 'WA',
     132                                  str(self.form['state'])))
     133        self.assertTrue(re.search(SELECTED_OPTION_PATTERN % 'QLD',
     134                                  str(self.form['state_required'])))
     135        self.assertTrue(re.search(INPUT_VALUE_PATTERN % '1234',
     136                                  str(self.form['postcode'])))
     137        self.assertTrue(re.search(INPUT_VALUE_PATTERN % '4321',
     138                                  str(self.form['postcode_required'])))               
  • tests/regressiontests/localflavor/models.py

     
    11from django.db import models
    22from django.contrib.localflavor.us.models import USStateField
     3from django.contrib.localflavor.au.models import AUStateField, AUPostCodeField
    34
    45class Place(models.Model):
    56    state = USStateField(blank=True)
    67    state_req = USStateField()
    78    state_default = USStateField(default="CA", blank=True)
    89    name = models.CharField(max_length=20)
     10
     11
     12class AustralianPlace(models.Model):
     13    state = AUStateField(blank=True)
     14    state_required = AUStateField()
     15    state_default = AUStateField(default="NSW", blank=True)
     16    postcode = AUPostCodeField(blank=True)
     17    postcode_required = AUPostCodeField()
     18    postcode_default = AUPostCodeField(default="2500", blank=True)
     19    name = models.CharField(max_length=20)
  • tests/regressiontests/localflavor/forms.py

     
    11from django.forms import ModelForm
    2 from models import Place
     2from models import Place, AustralianPlace
    33
    44class PlaceForm(ModelForm):
    55    """docstring for PlaceForm"""
    66    class Meta:
    77        model = Place
     8
     9class AustralianPlaceForm(ModelForm):
     10    """ Form for storing an Australian place. """
     11    class Meta:
     12        model = AustralianPlace       
  • docs/ref/contrib/localflavor.txt

     
    169169    A ``Select`` widget that uses a list of Australian states/territories as its
    170170    choices.
    171171
     172.. class:: au.models.AUPhoneNumberField
     173
     174    A model field that checks that the value is a valid Australian phone
     175    number (ten digits).
     176
     177.. class:: au.models.AUStateField
     178
     179    A model field that forms represent as a ``forms.AUStateField`` field and
     180    stores the three-letter Australian state abbreviation in the database.
     181
     182.. class:: au.models.AUPostCodeField
     183
     184    A model field that forms represent as a ``forms.AUPostCodeField`` field
     185    and stores the four-digit Australian postcode in the database.
     186
    172187Austria (``at``)
    173188================
    174189
Back to Top