Changeset 5235
- Timestamp:
- 05/14/07 10:58:54 (2 years ago)
- Files:
-
- django/branches/boulder-oracle-sprint/AUTHORS (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/django/conf/global_settings.py (modified) (1 diff)
- django/branches/boulder-oracle-sprint/django/conf/locale/bg (copied) (copied from django/trunk/django/conf/locale/bg)
- django/branches/boulder-oracle-sprint/django/conf/locale/bg/LC_MESSAGES (copied) (copied from django/trunk/django/conf/locale/bg/LC_MESSAGES)
- django/branches/boulder-oracle-sprint/django/conf/locale/bg/LC_MESSAGES/djangojs.mo (copied) (copied from django/trunk/django/conf/locale/bg/LC_MESSAGES/djangojs.mo)
- django/branches/boulder-oracle-sprint/django/conf/locale/bg/LC_MESSAGES/djangojs.po (copied) (copied from django/trunk/django/conf/locale/bg/LC_MESSAGES/djangojs.po)
- django/branches/boulder-oracle-sprint/django/conf/locale/bg/LC_MESSAGES/django.mo (copied) (copied from django/trunk/django/conf/locale/bg/LC_MESSAGES/django.mo)
- django/branches/boulder-oracle-sprint/django/conf/locale/bg/LC_MESSAGES/django.po (copied) (copied from django/trunk/django/conf/locale/bg/LC_MESSAGES/django.po)
- django/branches/boulder-oracle-sprint/django/contrib/localflavor/is_/forms.py (modified) (1 diff)
- django/branches/boulder-oracle-sprint/django/core/management.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/django/core/serializers/python.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/django/core/serializers/xml_serializer.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/django/db/backends/postgresql/base.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/django/db/backends/postgresql_psycopg2/base.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/django/newforms/forms.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/django/newforms/models.py (modified) (6 diffs)
- django/branches/boulder-oracle-sprint/django/test/testcases.py (modified) (7 diffs)
- django/branches/boulder-oracle-sprint/docs/databrowse.txt (modified) (1 diff)
- django/branches/boulder-oracle-sprint/docs/i18n.txt (modified) (1 diff)
- django/branches/boulder-oracle-sprint/docs/newforms.txt (modified) (14 diffs)
- django/branches/boulder-oracle-sprint/docs/testing.txt (modified) (5 diffs)
- django/branches/boulder-oracle-sprint/tests/modeltests/model_forms/models.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/tests/regressiontests/forms/regressions.py (modified) (1 diff)
- django/branches/boulder-oracle-sprint/tests/regressiontests/forms/tests.py (modified) (7 diffs)
- django/branches/boulder-oracle-sprint/tests/regressiontests/serializers_regress/models.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/tests/regressiontests/serializers_regress/tests.py (modified) (2 diffs)
- django/branches/boulder-oracle-sprint/tests/regressiontests/test_client_regress/models.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/branches/boulder-oracle-sprint/AUTHORS
r5178 r5235 79 79 Jure Cuhalev <gandalf@owca.info> 80 80 dackze+django@gmail.com 81 David Danier <goliath.mailinglist@gmx.de> 81 82 Dirk Datzert <dummy@habmalnefrage.de> 82 83 Jonathan Daugherty (cygnus) <http://www.cprogrammer.org/> … … 86 87 deric@monowerks.com 87 88 Max Derkachev <mderk@yandex.ru> 89 Jordan Dimov <s3x3y1@gmail.com> 88 90 dne@mayonnaise.net 89 91 Maximillian Dornseif <md@hudora.de> django/branches/boulder-oracle-sprint/django/conf/global_settings.py
r5148 r5235 39 39 ('ar', gettext_noop('Arabic')), 40 40 ('bn', gettext_noop('Bengali')), 41 ('bg', gettext_noop('Bulgarian')), 41 42 ('ca', gettext_noop('Catalan')), 42 43 ('cs', gettext_noop('Czech')), django/branches/boulder-oracle-sprint/django/contrib/localflavor/is_/forms.py
r5100 r5235 42 42 """ 43 43 check = [3, 2, 7, 6, 5, 4, 3, 2, 1, 0] 44 return sum( int(value[i]) * check[i] for i in range(10)) % 11 == 044 return sum([int(value[i]) * check[i] for i in range(10)]) % 11 == 0 45 45 46 46 def _format(self, value): django/branches/boulder-oracle-sprint/django/core/management.py
r5174 r5235 1464 1464 print "No %s fixture '%s' in %s." % \ 1465 1465 (format, fixture_name, humanize(fixture_dir)) 1466 1467 if count[0] > 0: 1468 sequence_sql = backend.get_sql_sequence_reset(style, models) 1469 if sequence_sql: 1470 if verbosity > 1: 1471 print "Resetting sequences" 1472 for line in sequence_sql: 1473 cursor.execute(line) 1474 1475 transaction.commit() 1476 transaction.leave_transaction_management() 1477 1466 1478 if count[0] == 0: 1467 1479 if verbosity > 0: … … 1470 1482 if verbosity > 0: 1471 1483 print "Installed %d object(s) from %d fixture(s)" % tuple(count) 1472 sequence_sql = backend.get_sql_sequence_reset(style, models)1473 if sequence_sql:1474 if verbosity > 1:1475 print "Resetting sequences"1476 for line in sequence_sql:1477 cursor.execute(line)1478 transaction.commit()1479 transaction.leave_transaction_management()1480 1484 1481 1485 load_data.help_doc = 'Installs the named fixture(s) in the database' django/branches/boulder-oracle-sprint/django/core/serializers/python.py
r4722 r5235 38 38 related = getattr(obj, field.name) 39 39 if related is not None: 40 related = related._get_pk_val()40 related = getattr(related, field.rel.field_name) 41 41 self._current[field.name] = related 42 42 … … 81 81 # Handle FK fields 82 82 elif field.rel and isinstance(field.rel, models.ManyToOneRel): 83 data[field.attname] = field.rel.to._meta.pk.to_python(field_value) 83 if field_value: 84 data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) 85 else: 86 data[field.attname] = None 84 87 85 88 # Handle all other fields django/branches/boulder-oracle-sprint/django/core/serializers/xml_serializer.py
r4755 r5235 83 83 related = getattr(obj, field.name) 84 84 if related is not None: 85 self.xml.characters(str( related._get_pk_val()))85 self.xml.characters(str(getattr(related, field.rel.field_name))) 86 86 else: 87 87 self.xml.addQuickElement("None") … … 182 182 return None 183 183 else: 184 return field.rel.to._meta. pk.to_python(184 return field.rel.to._meta.get_field(field.rel.field_name).to_python( 185 185 getInnerText(node).strip().encode(self.encoding)) 186 186 django/branches/boulder-oracle-sprint/django/db/backends/postgresql/base.py
r5100 r5235 243 243 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 244 244 (style.SQL_KEYWORD('SELECT'), 245 style.SQL_FIELD( '%s_%s_seq' % (model._meta.db_table, f.column)),245 style.SQL_FIELD(quote_name('%s_%s_seq' % (model._meta.db_table, f.column))), 246 246 style.SQL_KEYWORD('SELECT'), 247 247 style.SQL_FIELD(quote_name(f.column)), … … 252 252 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 253 253 (style.SQL_KEYWORD('SELECT'), 254 style.SQL_FIELD( '%s_id_seq' % f.m2m_db_table()),254 style.SQL_FIELD(quote_name('%s_id_seq' % f.m2m_db_table())), 255 255 style.SQL_KEYWORD('SELECT'), 256 256 style.SQL_FIELD(quote_name('id')), django/branches/boulder-oracle-sprint/django/db/backends/postgresql_psycopg2/base.py
r5079 r5235 200 200 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 201 201 (style.SQL_KEYWORD('SELECT'), 202 style.SQL_FIELD( '%s_%s_seq' % (model._meta.db_table, f.column)),202 style.SQL_FIELD(quote_name('%s_%s_seq' % (model._meta.db_table, f.column))), 203 203 style.SQL_KEYWORD('SELECT'), 204 204 style.SQL_FIELD(quote_name(f.column)), … … 209 209 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 210 210 (style.SQL_KEYWORD('SELECT'), 211 style.SQL_FIELD( '%s_id_seq' % f.m2m_db_table()),211 style.SQL_FIELD(quote_name('%s_id_seq' % f.m2m_db_table())), 212 212 style.SQL_KEYWORD('SELECT'), 213 213 style.SQL_FIELD(quote_name('id')), django/branches/boulder-oracle-sprint/django/newforms/forms.py
r5114 r5235 185 185 value = field.clean(value) 186 186 self.clean_data[name] = value 187 if hasattr(self, ' clean_%s' % name):188 value = getattr(self, ' clean_%s' % name)()187 if hasattr(self, 'do_clean_%s' % name): 188 value = getattr(self, 'do_clean_%s' % name)() 189 189 self.clean_data[name] = value 190 190 except ValidationError, e: … … 256 256 if not self.form.is_bound: 257 257 data = self.form.initial.get(self.name, self.field.initial) 258 if callable(data): 259 data = data() 258 260 else: 259 261 data = self.data django/branches/boulder-oracle-sprint/django/newforms/models.py
r4906 r5235 13 13 'ModelChoiceField', 'ModelMultipleChoiceField') 14 14 15 def model_save(self, commit=True): 16 """ 17 Creates and returns model instance according to self.clean_data. 18 19 This method is created for any form_for_model Form. 20 """ 21 if self.errors: 22 raise ValueError("The %s could not be created because the data didn't validate." % self._model._meta.object_name) 23 return save_instance(self, self._model(), commit) 24 25 def save_instance(form, instance, commit=True): 15 def save_instance(form, instance, fields=None, fail_message='saved', commit=True): 26 16 """ 27 17 Saves bound Form ``form``'s clean_data into model instance ``instance``. … … 34 24 opts = instance.__class__._meta 35 25 if form.errors: 36 raise ValueError("The %s could not be changed because the data didn't validate." % opts.object_name)26 raise ValueError("The %s could not be %s because the data didn't validate." % (opts.object_name, fail_message)) 37 27 clean_data = form.clean_data 38 28 for f in opts.fields: 39 29 if not f.editable or isinstance(f, models.AutoField) or not f.name in clean_data: 30 continue 31 if fields and f.name not in fields: 40 32 continue 41 33 setattr(instance, f.name, clean_data[f.name]) … … 43 35 instance.save() 44 36 for f in opts.many_to_many: 37 if fields and f.name not in fields: 38 continue 45 39 if f.name in clean_data: 46 40 setattr(instance, f.attname, clean_data[f.name]) … … 51 45 return instance 52 46 53 def make_ instance_save(instance):54 "Returns the save() method for a form_for_instanceForm."47 def make_model_save(model, fields, fail_message): 48 "Returns the save() method for a Form." 55 49 def save(self, commit=True): 56 return save_instance(self, instance, commit) 50 return save_instance(self, model(), fields, fail_message, commit) 51 return save 52 53 def make_instance_save(instance, fields, fail_message): 54 "Returns the save() method for a Form." 55 def save(self, commit=True): 56 return save_instance(self, instance, fields, fail_message, commit) 57 57 return save 58 58 59 def form_for_model(model, form=BaseForm, f ormfield_callback=lambda f: f.formfield()):59 def form_for_model(model, form=BaseForm, fields=None, formfield_callback=lambda f: f.formfield()): 60 60 """ 61 61 Returns a Form class for the given Django model class. … … 72 72 if not f.editable: 73 73 continue 74 if fields and not f.name in fields: 75 continue 74 76 formfield = formfield_callback(f) 75 77 if formfield: 76 78 field_list.append((f.name, formfield)) 77 fields = SortedDictFromList(field_list) 78 return type(opts.object_name + 'Form', (form,), {'base_fields': fields, '_model': model, 'save': model_save}) 79 base_fields = SortedDictFromList(field_list) 80 return type(opts.object_name + 'Form', (form,), 81 {'base_fields': base_fields, '_model': model, 'save': make_model_save(model, fields, 'created')}) 79 82 80 def form_for_instance(instance, form=BaseForm, f ormfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):83 def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 81 84 """ 82 85 Returns a Form class for the given Django model instance. … … 95 98 if not f.editable: 96 99 continue 100 if fields and not f.name in fields: 101 continue 97 102 current_value = f.value_from_object(instance) 98 103 formfield = formfield_callback(f, initial=current_value) 99 104 if formfield: 100 105 field_list.append((f.name, formfield)) 101 fields = SortedDictFromList(field_list)106 base_fields = SortedDictFromList(field_list) 102 107 return type(opts.object_name + 'InstanceForm', (form,), 103 {'base_fields': fields, '_model': model, 'save': make_instance_save(instance)})108 {'base_fields': base_fields, '_model': model, 'save': make_instance_save(instance, fields, 'changed')}) 104 109 105 110 def form_for_fields(field_list): django/branches/boulder-oracle-sprint/django/test/testcases.py
r5183 r5235 46 46 management.load_data(self.fixtures, verbosity=0) 47 47 mail.outbox = [] 48 49 def run(self, result=None):50 """ Wrapper around default run method to perform common Django test set up.51 This means that user-defined Test Cases aren't required to include a call52 to super().setUp().53 48 49 def __call__(self, result=None): 50 """ 51 Wrapper around default __call__ method to perform common Django test 52 set up. This means that user-defined Test Cases aren't required to 53 include a call to super().setUp(). 54 54 """ 55 55 self.client = Client() 56 56 self._pre_setup() 57 super(TestCase, self). run(result)57 super(TestCase, self).__call__(result) 58 58 59 59 def assertRedirects(self, response, expected_path, status_code=302, target_status_code=200): … … 63 63 """ 64 64 self.assertEqual(response.status_code, status_code, 65 "Response didn't redirect : Reponse code was %d (expected %d)" %65 "Response didn't redirect as expected: Reponse code was %d (expected %d)" % 66 66 (response.status_code, status_code)) 67 67 scheme, netloc, path, params, query, fragment = urlparse(response['Location']) … … 71 71 self.assertEqual(redirect_response.status_code, target_status_code, 72 72 "Couldn't retrieve redirection page '%s': response code was %d (expected %d)" % 73 (path, re sponse.status_code,status_code))73 (path, redirect_response.status_code, target_status_code)) 74 74 75 75 def assertContains(self, response, text, count=1, status_code=200): … … 109 109 if field: 110 110 if field in context[form].errors: 111 self. assertTrue(err in context[form].errors[field],111 self.failUnless(err in context[form].errors[field], 112 112 "The field '%s' on form '%s' in context %d does not contain the error '%s' (actual errors: %s)" % 113 113 (field, form, i, err, list(context[form].errors[field]))) … … 118 118 self.fail("The form '%s' in context %d does not contain the field '%s'" % (form, i, field)) 119 119 else: 120 self. assertTrue(err in context[form].non_field_errors(),120 self.failUnless(err in context[form].non_field_errors(), 121 121 "The form '%s' in context %d does not contain the non-field error '%s' (actual errors: %s)" % 122 122 (form, i, err, list(context[form].non_field_errors()))) … … 128 128 if isinstance(response.template, list): 129 129 template_names = [t.name for t in response.template] 130 self. assertTrue(template_name in template_names,130 self.failUnless(template_name in template_names, 131 131 "Template '%s' was not one of the templates used to render the response. Templates used: %s" % 132 132 (template_name, template_names)) … … 141 141 "Assert that the template with the provided name was NOT used in rendering the response" 142 142 if isinstance(response.template, list): 143 self. assertFalse(template_name in [t.name for t in response.template],143 self.failIf(template_name in [t.name for t in response.template], 144 144 "Template '%s' was used unexpectedly in rendering the response" % template_name) 145 145 elif response.template: django/branches/boulder-oracle-sprint/docs/databrowse.txt
r5014 r5235 45 45 some point. A good place for it is in your URLconf file (``urls.py``). 46 46 47 3. Add the following line to your URLconf:: 47 3. Change your URLconf to import the ``databrowse`` module:: 48 49 from django.contrib import databrowse 50 51 ...and add the following line to your URLconf:: 48 52 49 53 (r'^databrowse/(.*)', databrowse.site.root), django/branches/boulder-oracle-sprint/docs/i18n.txt
r5174 r5235 237 237 ``{% endblocktrans %}``. Example:: 238 238 239 {% blocktrans count list| countas counter %}239 {% blocktrans count list|length as counter %} 240 240 There is only one {{ name }} object. 241 241 {% plural %} django/branches/boulder-oracle-sprint/docs/newforms.txt
r4842 r5235 10 10 ============== 11 11 12 ``django.newforms`` currently is only available in Django beginning 13 with the 0.96 release. the Django development version -- i.e., it's 14 not available in the Django 0.95 release. For the next Django release, 15 our plan is to do the following: 16 17 * As of revision [4208], we've copied the current ``django.forms`` to 18 ``django.oldforms``. This allows you to upgrade your code *now* rather 19 than waiting for the backwards-incompatible change and rushing to fix 20 your code after the fact. Just change your import statements like this:: 12 ``django.newforms`` is new in Django's 0.96 release, but, as it won't be new 13 forever, we plan to rename it to ``django.forms`` in the future. The current 14 ``django.forms`` package will be available as ``django.oldforms`` until Django 15 1.0, when we plan to remove it for good. 16 17 That has direct repercussions on the forward compatibility of your code. Please 18 read the following migration plan and code accordingly: 19 20 * The old forms framework (the current ``django.forms``) has been copied to 21 ``django.oldforms``. Thus, you can start upgrading your code *now*, 22 rather than waiting for the future backwards-incompatible change, by 23 changing your import statements like this:: 21 24 22 25 from django import forms # old 23 26 from django import oldforms as forms # new 24 27 25 * At an undecided future date, we will move the current ``django.newforms``26 to ``django.forms``. This will be a backwards-incompatible change, and27 anybody who is still using the old version of ``django.forms`` at that28 time will need to change their import statements, as described in the29 previous bullet.28 * In the next Django release (0.97), we will move the current 29 ``django.newforms`` to ``django.forms``. This will be a 30 backwards-incompatible change, and anybody who is still using the old 31 version of ``django.forms`` at that time will need to change their import 32 statements, as described in the previous bullet. 30 33 31 34 * We will remove ``django.oldforms`` in the release *after* the next Django 32 release -- the release that comes after the release in which we're 33 creating the new ``django.forms``. 35 release -- either 0.98 or 1.0, whichever comes first. 34 36 35 37 With this in mind, we recommend you use the following import statement when … … 185 187 False 186 188 187 Access the `` Form`` attribute ``errors``to get a dictionary of error messages::189 Access the ``errors`` attribute to get a dictionary of error messages:: 188 190 189 191 >>> f.errors … … 197 199 form's data will be validated the first time either you call ``is_valid()`` or 198 200 access ``errors``. 201 202 The validation routines will only get called once, regardless of how many times 203 you access ``errors`` or call ``is_valid()``. This means that if validation has 204 side effects, those side effects will only be triggered once. 199 205 200 206 Behavior of unbound forms … … 274 280 >>> f.clean_data # Doesn't contain extra_field_1, etc. 275 281 {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} 282 283 ``clean_data`` will include a key and value for *all* fields defined in the 284 ``Form``, even if the data didn't include a value for fields that are not 285 required. In this example, the data dictionary doesn't include a value for the 286 ``nick_name`` field, but ``clean_data`` includes it, with an empty value:: 287 288 >>> class OptionalPersonForm(Form): 289 ... first_name = CharField() 290 ... last_name = CharField() 291 ... nick_name = CharField(required=False) 292 >>> data = {'first_name': u'John', 'last_name': u'Lennon'} 293 >>> f = OptionalPersonForm(data) 294 >>> f.is_valid() 295 True 296 >>> f.clean_data 297 {'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'} 298 299 In this above example, the ``clean_data`` value for ``nick_name`` is set to an 300 empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat 301 empty values as an empty string. Each field type knows what its "blank" value 302 is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. 276 303 277 304 Behavior of unbound forms … … 455 482 then the form output will include ``<label>`` tags, and will generate ``id`` 456 483 attributes based on the format string. For example, for a format string 457 ``'field_%s'``, a field named ``subject`` will get the ``id`` 484 ``'field_%s'``, a field named ``subject`` will get the ``id`` value 458 485 ``'field_subject'``. Continuing our example:: 459 486 … … 494 521 If you render a bound ``Form`` object, the act of rendering will automatically 495 522 run the form's validation if it hasn't already happened, and the HTML output 496 will include the validation errors as a ``<ul>`` near the field. The particular 497 positioning of the error messages depends on the output method you're using:: 523 will include the validation errors as a ``<ul class="errorlist">`` near the 524 field. The particular positioning of the error messages depends on the output 525 method you're using:: 498 526 499 527 >>> data = {'subject': '', … … 557 585 558 586 For a field's list of errors, access the field's ``errors`` attribute. This 559 is a list-like object that is displayed as an HTML ``<ul>`` when printed:: 587 is a list-like object that is displayed as an HTML ``<ul class="errorlist">`` 588 when printed:: 560 589 561 590 >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''} … … 647 676 Each ``Field`` class constructor takes at least these arguments. Some 648 677 ``Field`` classes take additional, field-specific arguments, but the following 649 should *always* be a vailable:678 should *always* be accepted: 650 679 651 680 ``required`` … … 705 734 field. This is used when the ``Field`` is displayed in a ``Form``. 706 735 707 As explained in _`Outputting forms as HTML`above, the default label for a736 As explained in "Outputting forms as HTML" above, the default label for a 708 737 ``Field`` is generated from the field name by converting all underscores to 709 738 spaces and upper-casing the first letter. Specify ``label`` if that default … … 780 809 781 810 The ``widget`` argument lets you specify a ``Widget`` class to use when 782 rendering this ``Field``. See _`Widgets`below for more information.811 rendering this ``Field``. See "Widgets" below for more information. 783 812 784 813 ``help_text`` … … 787 816 The ``help_text`` argument lets you specify descriptive text for this 788 817 ``Field``. If you provide ``help_text``, it will be displayed next to the 789 ``Field`` when the ``Field`` is rendered in a ``Form``. 818 ``Field`` when the ``Field`` is rendered by one of the convenience ``Form`` 819 methods (e.g., ``as_ul()``). 790 820 791 821 Here's a full example ``Form`` that implements ``help_text`` for two of its … … 861 891 <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> 862 892 893 Built-in ``Field`` classes 894 -------------------------- 895 896 Naturally, the ``newforms`` library comes with a set of ``Field`` classes that 897 represent common validation needs. This section documents each built-in field. 898 899 For each field, we describe the default widget used if you don't specify 900 ``widget``. We also specify the value returned when you provide an empty value 901 (see the section on ``required`` above to understand what that means). 902 903 ``BooleanField`` 904 ~~~~~~~~~~~~~~~~ 905 906 * Default widget: ``CheckboxInput`` 907 * Empty value: ``None`` 908 * Normalizes to: A Python ``True`` or ``False`` value. 909 * Validates nothing (i.e., it never raises a ``ValidationError``). 910 911 ``CharField`` 912 ~~~~~~~~~~~~~ 913 914 * Default widget: ``TextInput`` 915 * Empty value: ``''`` (an empty string) 916 * Normalizes to: A Unicode object. 917 * Validates nothing, unless ``max_length`` or ``min_length`` is provided. 918 919 Has two optional arguments for validation, ``max_length`` and ``min_length``. 920 If provided, these arguments ensure that the string is at most or at least the 921 given length. 922 923 ``ChoiceField`` 924 ~~~~~~~~~~~~~~~ 925 926 * Default widget: ``Select`` 927 * Empty value: ``''`` (an empty string) 928 * Normalizes to: A Unicode object. 929 * Validates that the given value exists in the list of choices. 930 931 Takes one extra argument, ``choices``, which is an iterable (e.g., a list or 932 tuple) of 2-tuples to use as choices for this field. 933 934 ``DateField`` 935 ~~~~~~~~~~~~~ 936 937 * Default widget: ``TextInput`` 938 * Empty value: ``None`` 939 * Normalizes to: A Python ``datetime.date`` object. 940 * Validates that the given value is either a ``datetime.date``, 941 ``datetime.datetime`` or string formatted in a particular date format. 942 943 Takes one optional argument, ``input_formats``, which is a list of formats used 944 to attempt to convert a string to a valid ``datetime.date`` object. 945 946 If no ``input_formats`` argument is provided, the default input formats are:: 947 948 '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' 949 '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' 950 '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' 951 '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' 952 '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' 953 954 ``DateTimeField`` 955 ~~~~~~~~~~~~~~~~~ 956 957 * Default widget: ``TextInput`` 958 * Empty value: ``None`` 959 * Normalizes to: A Python ``datetime.datetime`` object. 960 * Validates that the given value is either a ``datetime.datetime``, 961 ``datetime.date`` or string formatted in a particular datetime format. 962 963 Takes one optional argument, ``input_formats``, which is a list of formats used 964 to attempt to convert a string to a valid ``datetime.datetime`` object. 965 966 If no ``input_formats`` argument is provided, the default input formats are:: 967 968 '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' 969 '%Y-%m-%d %H:%M', # '2006-10-25 14:30' 970 '%Y-%m-%d', # '2006-10-25' 971 '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' 972 '%m/%d/%Y %H:%M', # '10/25/2006 14:30' 973 '%m/%d/%Y', # '10/25/2006' 974 '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' 975 '%m/%d/%y %H:%M', # '10/25/06 14:30' 976 '%m/%d/%y', # '10/25/06' 977 978 ``EmailField`` 979 ~~~~~~~~~~~~~~ 980 981 * Default widget: ``TextInput`` 982 * Empty value: ``''`` (an empty string) 983 * Normalizes to: A Unicode object. 984 * Validates that the given value is a valid e-mail address, using a 985 moderately complex regular expression. 986 987 Has two optional arguments for validation, ``max_length`` and ``min_length``. 988 If provided, these arguments ensure that the string is at most or at least the 989 given length. 990 991 ``IntegerField`` 992 ~~~~~~~~~~~~~~~~ 993 994 * Default widget: ``TextInput`` 995 * Empty value: ``None`` 996 * Normalizes to: A Python integer or long integer. 997 * Validates that the given value is an integer. Leading and trailing 998 whitespace is allowed, as in Python's ``int()`` function. 999 1000 ``MultipleChoiceField`` 1001 ~~~~~~~~~~~~~~~~~~~~~~~ 1002 1003 * Default widget: ``SelectMultiple`` 1004 * Empty value: ``[]`` (an empty list) 1005 * Normalizes to: A list of Unicode objects. 1006 * Validates that every value in the given list of values exists in the list 1007 of choices. 1008 1009 Takes one extra argument, ``choices``, which is an iterable (e.g., a list or 1010 tuple) of 2-tuples to use as choices for this field. 1011 1012 ``NullBooleanField`` 1013 ~~~~~~~~~~~~~~~~~~~~ 1014 1015 * Default widget: ``NullBooleanSelect`` 1016 * Empty value: ``None`` 1017 * Normalizes to: A Python ``True``, ``False`` or ``None`` value. 1018 * Validates nothing (i.e., it never raises a ``ValidationError``). 1019 1020 ``RegexField`` 1021 ~~~~~~~~~~~~~~ 1022 1023 * Default widget: ``TextInput`` 1024 * Empty value: ``''`` (an empty string) 1025 * Normalizes to: A Unicode object. 1026 * Validates that the given value matches against a certain regular 1027 expression. 1028 1029 Takes one required argument, ``regex``, which is a regular expression specified 1030 either as a string or a compiled regular expression object. 1031 1032 Also takes the following optional arguments: 1033 1034 ====================== ===================================================== 1035 Argument Description 1036 ====================== ===================================================== 1037 ``max_length`` Ensures the string has at most this many characters. 1038 ``min_length`` Ensures the string has at least this many characters. 1039 ``error_message`` Error message to return for failed validation. If no 1040 message is provided, a generic error message will be 1041 used. 1042 ====================== ===================================================== 1043 1044 ``TimeField`` 1045 ~~~~~~~~~~~~~ 1046 1047 * Default widget: ``TextInput`` 1048 * Empty value: ``None`` 1049 * Normalizes to: A Python ``datetime.time`` object. 1050 * Validates that the given value is either a ``datetime.time`` or string 1051 formatted in a particular time format. 1052 1053 Takes one optional argument, ``input_formats``, which is a list of formats used 1054 to attempt to convert a string to a valid ``datetime.time`` object. 1055 1056 If no ``input_formats`` argument is provided, the default input formats are:: 1057 1058 '%H:%M:%S', # '14:30:59' 1059 '%H:%M', # '14:30' 1060 1061 ``URLField`` 1062 ~~~~~~~~~~~~ 1063 1064 * Default widget: ``TextInput`` 1065 * Empty value: ``''`` (an empty string) 1066 * Normalizes to: A Unicode object. 1067 * Validates that the given value is a valid URL. 1068 1069 Takes the following optional arguments: 1070 1071 ======================== ===================================================== 1072 Argument Description 1073 ======================== ===================================================== 1074 ``max_length`` Ensures the string has at most this many characters. 1075 ``min_length`` Ensures the string has at least this many characters. 1076 ``verify_exists`` If ``True``, the validator will attempt to load the 1077 given URL, raising ``ValidationError`` if the page 1078 gives a 404. Defaults to ``False``. 1079 ``validator_user_agent`` String used as the user-agent used when checking for 1080 a URL's existence. Defaults to the value of the 1081 ``URL_VALIDATOR_USER_AGENT`` setting. 1082 ======================== ===================================================== 1083 1084 Slightly complex built-in ``Field`` classes 1085 ------------------------------------------- 1086 1087 The following are not yet documented here. See the unit tests, linked-to from 1088 the bottom of this document, for examples of their use. 1089 1090 ``ComboField`` 1091 ~~~~~~~~~~~~~~ 1092 1093 ``MultiValueField`` 1094 ~~~~~~~~~~~~~~~~~~~ 1095 1096 ``SplitDateTimeField`` 1097 ~~~~~~~~~~~~~~~~~~~~~~ 1098 863 1099 Creating custom fields 864 1100 ---------------------- … … 871 1107 ``help_text``). 872 1108 1109 Generating forms for models 1110 =========================== 1111 1112 If you're building a database-driven app, chances are you'll have forms that 1113 map closely to Django models. For instance, you might have a ``BlogComment`` 1114 model, and you want to create a form that lets people submit comments. In this 1115 case, it would be redundant to define the field types in your form, because 1116 you've already defined the fields in your model. 1117 1118 For this reason, Django provides a few helper functions that let you create a 1119 ``Form`` class from a Django model. 1120 1121 ``form_for_model()`` 1122 -------------------- 1123 1124 The method ``django.newforms.form_for_model()`` creates a form based on the 1125 definition of a specific model. Pass it the model class, and it will return a 1126 ``Form`` class that contains a form field for each model field. 1127 1128 For example:: 1129 1130 >>> from django.newforms import form_for_model 1131 1132 # Create the form class. 1133 >>> ArticleForm = form_for_model(Article) 1134 1135 # Create an empty form instance. 1136 >>> f = ArticleForm() 1137 1138 It bears repeating that ``form_for_model()`` takes the model *class*, not a 1139 model instance, and it returns a ``Form`` *class*, not a ``Form`` instance. 1140 1141 Field types 1142 ~~~~~~~~~~~ 1143 1144 The generated ``Form`` class will have a form field for every model field. Each 1145 model field has a corresponding default form field. For example, a 1146 ``CharField`` on a model is represented as a ``CharField`` on a form. A 1147 model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is 1148 the full list of conversions: 1149 1150 =============================== ======================================== 1151 Model field Form field 1152 =============================== ======================================== 1153 ``AutoField`` Not represented in the form 1154 ``BooleanField`` ``BooleanField`` 1155 ``CharField`` ``CharField`` with ``max_length`` set to 1156 the model field's ``maxlength`` 1157 ``CommaSeparatedIntegerField`` ``CharField`` 1158 ``DateField`` ``DateField`` 1159 ``DateTimeField`` ``DateTimeField`` 1160 ``EmailField`` ``EmailField`` 1161 ``FileField`` ``CharField`` 1162 ``FilePathField`` ``CharField`` 1163 ``FloatField`` ``CharField`` 1164 ``ForeignKey`` ``ModelChoiceField`` (see below) 1165 ``ImageField`` ``CharField`` 1166 ``IntegerField`` ``IntegerField`` 1167 ``IPAddressField`` ``CharField`` 1168 ``ManyToManyField`` ``ModelMultipleChoiceField`` (see 1169 below) 1170 ``NullBooleanField`` ``CharField`` 1171 ``PhoneNumberField`` ``USPhoneNumberField`` 1172 (from ``django.contrib.localflavor.us``) 1173 ``PositiveIntegerField`` ``IntegerField`` 1174 ``PositiveSmallIntegerField`` ``IntegerField``
