Changeset 5214
- Timestamp:
- 05/13/07 01:23:30 (2 years ago)
- Files:
-
- django/branches/unicode (modified) (1 prop)
- django/branches/unicode/AUTHORS (modified) (1 diff)
- django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/djangojs.mo (modified) (previous)
- django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/djangojs.po (modified) (1 diff)
- django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/django.mo (modified) (previous)
- django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/django.po (modified) (1 diff)
- django/branches/unicode/django/contrib/localflavor/is_/forms.py (modified) (1 diff)
- django/branches/unicode/django/contrib/webdesign/__init__.py (modified) (1 prop)
- django/branches/unicode/django/contrib/webdesign/lorem_ipsum.py (modified) (1 diff, 1 prop)
- django/branches/unicode/django/contrib/webdesign/templatetags/__init__.py (modified) (1 prop)
- django/branches/unicode/django/contrib/webdesign/templatetags/webdesign.py (modified) (1 prop)
- django/branches/unicode/django/db/backends/postgresql/base.py (modified) (2 diffs)
- django/branches/unicode/django/db/backends/postgresql_psycopg2/base.py (modified) (2 diffs)
- django/branches/unicode/django/http/__init__.py (modified) (1 diff)
- django/branches/unicode/django/newforms/forms.py (modified) (1 diff)
- django/branches/unicode/django/newforms/models.py (modified) (6 diffs)
- django/branches/unicode/django/test/testcases.py (modified) (6 diffs)
- django/branches/unicode/docs/i18n.txt (modified) (1 diff)
- django/branches/unicode/docs/install.txt (modified) (3 diffs)
- django/branches/unicode/docs/newforms.txt (modified) (2 diffs)
- django/branches/unicode/docs/templates_python.txt (modified) (3 diffs)
- django/branches/unicode/docs/testing.txt (modified) (5 diffs)
- django/branches/unicode/tests/modeltests/model_forms/models.py (modified) (2 diffs)
- django/branches/unicode/tests/regressiontests/forms/tests.py (modified) (1 diff)
- django/branches/unicode/tests/regressiontests/httpwrappers/tests.py (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/branches/unicode
- Property svnmerge-integrated changed from /django/trunk:1-5184 to /django/trunk:1-5213
django/branches/unicode/AUTHORS
r5193 r5214 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/> django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/djangojs.po
r3827 r5214 47 47 #: contrib/admin/media/js/calendar.js:24 48 48 msgid "January February March April May June July August September October November December" 49 msgstr "一月 二月 三月 四月 五月 六月 六月七月 八月 九月 十月 十一月 十二月"49 msgstr "一月 二月 三月 四月 五月 六月 七月 八月 九月 十月 十一月 十二月" 50 50 51 51 #: contrib/admin/media/js/dateparse.js:33 django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/django.po
r3827 r5214 1345 1345 #: utils/dates.py:19 1346 1346 msgid "may" 1347 msgstr " 三月"1347 msgstr "五月" 1348 1348 1349 1349 #: utils/dates.py:19 django/branches/unicode/django/contrib/localflavor/is_/forms.py
r5126 r5214 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/unicode/django/contrib/webdesign/__init__.py
- Property svn:eol-style set to native
django/branches/unicode/django/contrib/webdesign/lorem_ipsum.py
- Property svn:eol-style set to native
r4857 r5214 60 60 c = len(word_list) 61 61 if count > c: 62 count = min(count - c, len(WORDS)) 63 word_list += random.sample(WORDS, count - c) 62 count -= c 63 while count > 0: 64 c = min(count, len(WORDS)) 65 count -= c 66 word_list += random.sample(WORDS, c) 64 67 else: 65 68 word_list = word_list[:count] django/branches/unicode/django/contrib/webdesign/templatetags/__init__.py
- Property svn:eol-style set to native
django/branches/unicode/django/contrib/webdesign/templatetags/webdesign.py
- Property svn:eol-style set to native
django/branches/unicode/django/db/backends/postgresql/base.py
r5126 r5214 234 234 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 235 235 (style.SQL_KEYWORD('SELECT'), 236 style.SQL_FIELD( '%s_%s_seq' % (model._meta.db_table, f.column)),236 style.SQL_FIELD(quote_name('%s_%s_seq' % (model._meta.db_table, f.column))), 237 237 style.SQL_KEYWORD('SELECT'), 238 238 style.SQL_FIELD(quote_name(f.column)), … … 243 243 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 244 244 (style.SQL_KEYWORD('SELECT'), 245 style.SQL_FIELD( '%s_id_seq' % f.m2m_db_table()),245 style.SQL_FIELD(quote_name('%s_id_seq' % f.m2m_db_table())), 246 246 style.SQL_KEYWORD('SELECT'), 247 247 style.SQL_FIELD(quote_name('id')), django/branches/unicode/django/db/backends/postgresql_psycopg2/base.py
r5081 r5214 185 185 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 186 186 (style.SQL_KEYWORD('SELECT'), 187 style.SQL_FIELD( '%s_%s_seq' % (model._meta.db_table, f.column)),187 style.SQL_FIELD(quote_name('%s_%s_seq' % (model._meta.db_table, f.column))), 188 188 style.SQL_KEYWORD('SELECT'), 189 189 style.SQL_FIELD(quote_name(f.column)), … … 194 194 output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 195 195 (style.SQL_KEYWORD('SELECT'), 196 style.SQL_FIELD( '%s_id_seq' % f.m2m_db_table()),196 style.SQL_FIELD(quote_name('%s_id_seq' % f.m2m_db_table())), 197 197 style.SQL_KEYWORD('SELECT'), 198 198 style.SQL_FIELD(quote_name('id')), django/branches/unicode/django/http/__init__.py
r5197 r5214 109 109 MultiValueDict.__setitem__(self, key, value) 110 110 111 def __delitem__(self, key): 112 self._assert_mutable() 113 super(QueryDict, self).__delitem__(key) 114 111 115 def get(self, key, default=None): 112 116 return str_to_unicode(MultiValueDict.get(self, key, default), self.encoding) django/branches/unicode/django/newforms/forms.py
r5126 r5214 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/unicode/django/newforms/models.py
r4878 r5214 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/unicode/django/test/testcases.py
r5185 r5214 1 1 import re, doctest, unittest 2 import sys 2 3 from urlparse import urlparse 3 4 from django.db import transaction … … 46 47 management.load_data(self.fixtures, verbosity=0) 47 48 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 49 50 def __call__(self, result=None): 51 """ 52 Wrapper around default __call__ method to perform common Django test 53 set up. This means that user-defined Test Cases aren't required to 54 include a call to super().setUp(). 54 55 """ 55 56 self.client = Client() 56 57 self._pre_setup() 57 super(TestCase, self). run(result)58 super(TestCase, self).__call__(result) 58 59 59 60 def assertRedirects(self, response, expected_path, status_code=302, target_status_code=200): … … 109 110 if field: 110 111 if field in context[form].errors: 111 self. assertTrue(err in context[form].errors[field],112 self.failUnless(err in context[form].errors[field], 112 113 "The field '%s' on form '%s' in context %d does not contain the error '%s' (actual errors: %s)" % 113 114 (field, form, i, err, list(context[form].errors[field]))) … … 118 119 self.fail("The form '%s' in context %d does not contain the field '%s'" % (form, i, field)) 119 120 else: 120 self. assertTrue(err in context[form].non_field_errors(),121 self.failUnless(err in context[form].non_field_errors(), 121 122 "The form '%s' in context %d does not contain the non-field error '%s' (actual errors: %s)" % 122 123 (form, i, err, list(context[form].non_field_errors()))) … … 128 129 if isinstance(response.template, list): 129 130 template_names = [t.name for t in response.template] 130 self. assertTrue(template_name in template_names,131 self.failUnless(template_name in template_names, 131 132 u"Template '%s' was not one of the templates used to render the response. Templates used: %s" % 132 133 (template_name, u', '.join(template_names))) … … 141 142 "Assert that the template with the provided name was NOT used in rendering the response" 142 143 if isinstance(response.template, list): 143 self. assertFalse(template_name in [t.name for t in response.template],144 self.failIf(template_name in [t.name for t in response.template], 144 145 u"Template '%s' was used unexpectedly in rendering the response" % template_name) 145 146 elif response.template: 146 147 self.assertNotEqual(template_name, response.template.name, 147 148 u"Template '%s' was used unexpectedly in rendering the response" % template_name) 148 149 django/branches/unicode/docs/i18n.txt
r5185 r5214 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/unicode/docs/install.txt
r5126 r5214 57 57 58 58 If you're on Windows, check out the unofficial `compiled Windows version`_. 59 59 60 60 * If you're using MySQL, you'll need MySQLdb_, version 1.2.1p2 or higher. 61 61 You will also want to read the database-specific notes for the `MySQL backend`_. … … 76 76 ================================= 77 77 78 If you are upgrading your installation of Django from a previous version, 79 you will need to uninstall the old Django version before installing the 80 new version. 78 If you are upgrading your installation of Django from a previous version, 79 you will need to uninstall the old Django version before installing the 80 new version. 81 81 82 82 If you installed Django using ``setup.py install``, uninstalling 83 is as simple as deleting the ``django`` directory from your Python 83 is as simple as deleting the ``django`` directory from your Python 84 84 ``site-packages``. 85 85 86 If you installed Django from a Python Egg, remove the Django ``.egg` file,87 and remove the reference to the egg in the file named ``easy-install.pth``. 86 If you installed Django from a Python Egg, remove the Django ``.egg`` file, 87 and remove the reference to the egg in the file named ``easy-install.pth``. 88 88 This file should also be located in your ``site-packages`` directory. 89 89 … … 93 93 system, and the location in which Python was installed. However, the 94 94 following locations are common: 95 95 96 96 * If you're using Linux: ``/usr/lib/python2.X/site-packages`` 97 97 django/branches/unicode/docs/newforms.txt
r4819 r5214 871 871 ``help_text``). 872 872 873 Generating forms for models 874 =========================== 875 876 If you're building a database-driven app, chances are you'll have forms that 877 map closely to Django models. For instance, you might have a ``BlogComment`` 878 model, and you want to create a form that lets people submit comments. In this 879 case, it would be redundant to define the field types in your form, because 880 you've already defined the fields in your model. 881 882 For this reason, Django provides a few helper functions that let you create a 883 ``Form`` class from a Django model. 884 885 ``form_for_model()`` 886 -------------------- 887 888 The method ``django.newforms.form_for_model()`` creates a form based on the 889 definition of a specific model. Pass it the model class, and it will return a 890 ``Form`` class that contains a form field for each model field. 891 892 For example:: 893 894 >>> from django.newforms import form_for_model 895 896 # Create the form class. 897 >>> ArticleForm = form_for_model(Article) 898 899 # Create an empty form instance. 900 >>> f = ArticleForm() 901 902 It bears repeating that ``form_for_model()`` takes the model *class*, not a 903 model instance, and it returns a ``Form`` *class*, not a ``Form`` instance. 904 905 Field types 906 ~~~~~~~~~~~ 907 908 The generated ``Form`` class will have a form field for every model field. Each 909 model field has a corresponding default form field. For example, a 910 ``CharField`` on a model is represented as a ``CharField`` on a form. A 911 model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is 912 the full list of conversions: 913 914 =============================== ======================================== 915 Model field Form field 916 =============================== ======================================== 917 ``AutoField`` Not represented in the form 918 ``BooleanField`` ``BooleanField`` 919 ``CharField`` ``CharField`` with ``max_length`` set to 920 the model field's ``maxlength`` 921 ``CommaSeparatedIntegerField`` ``CharField`` 922 ``DateField`` ``DateField`` 923 ``DateTimeField`` ``DateTimeField`` 924 ``EmailField`` ``EmailField`` 925 ``FileField`` ``CharField`` 926 ``FilePathField`` ``CharField`` 927 ``FloatField`` ``CharField`` 928 ``ForeignKey`` ``ModelChoiceField`` (see below) 929 ``ImageField`` ``CharField`` 930 ``IntegerField`` ``IntegerField`` 931 ``IPAddressField`` ``CharField`` 932 ``ManyToManyField`` ``ModelMultipleChoiceField`` (see 933 below) 934 ``NullBooleanField`` ``CharField`` 935 ``PhoneNumberField`` ``USPhoneNumberField`` 936 (from ``django.contrib.localflavor.us``) 937 ``PositiveIntegerField`` ``IntegerField`` 938 ``PositiveSmallIntegerField`` ``IntegerField`` 939 ``SlugField`` ``CharField`` 940 ``SmallIntegerField`` ``IntegerField`` 941 ``TextField`` ``CharField`` with ``widget=Textarea`` 942 ``TimeField`` ``TimeField`` 943 ``URLField`` ``URLField`` with ``verify_exists`` set 944 to the model field's ``verify_exists`` 945 ``USStateField`` ``CharField`` with 946 ``widget=USStateSelect`` 947 (``USStateSelect`` is from 948 ``django.contrib.localflavor.us``) 949 ``XMLField`` ``CharField`` with ``widget=Textarea`` 950 =============================== ======================================== 951 952 As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field 953 types are special cases: 954 955 * ``ForeignKey`` is represented by ``django.newforms.ModelChoiceField``, 956 which is a ``ChoiceField`` whose choices are a model ``QuerySet``. 957 958 * ``ManyToManyField`` is represented by 959 ``django.newforms.ModelMultipleChoiceField``, which is a 960 ``MultipleChoiceField`` whose choices are a model ``QuerySet``. 961 962 In addition, each generated form field has attributes set as follows: 963 964 * If the model field has ``blank=True``, then ``required`` is set to 965 ``False`` on the form field. Otherwise, ``required=True``. 966 967 * The form field's ``label`` is set to the ``verbose_name`` of the model 968 field, with the first character capitalized. 969 970 * The form field's ``help_text`` is set to the ``help_text`` of the model 971 field. 972 973 * If the model field has ``choices`` set, then the form field's ``widget`` 974 will be set to ``Select``, with choices coming from the model field's 975 ``choices``. 976 977 Finally, note that you can override the form field used for a given model 978 field. See "Overriding the default field types" below. 979 980 A full example 981 ~~~~~~~~~~~~~~ 982 983 Consider this set of models:: 984 985 from django.db import models 986 987 TITLE_CHOICES = ( 988 ('MR', 'Mr.'), 989 ('MRS', 'Mrs.'), 990 ('MS', 'Ms.'), 991 ) 992 993 class Author(models.Model): 994 name = models.CharField(maxlength=100) 995 title = models.CharField(maxlength=3, choices=TITLE_CHOICES) 996 birth_date = models.DateField(blank=True, null=True) 997 998 def __str__(self): 999 return self.name 1000 1001 class Book(models.Model): 1002 name = models.CharField(maxlength=100) 1003 authors = models.ManyToManyField(Author) 1004 1005 With these models, a call to ``form_for_model(Author)`` would return a ``Form`` 1006 class equivalent to this:: 1007 1008 class AuthorForm(forms.Form): 1009 name = forms.CharField(max_length=100) 1010 title = forms.CharField(max_length=3, 1011 widget=forms.Select(choices=TITLE_CHOICES)) 1012 birth_date = forms.DateField(required=False) 1013 1014 A call to ``form_for_model(Book)`` would return a ``Form`` class equivalent to 1015 this:: 1016 1017 class BookForm(forms.Form): 1018 name = forms.CharField(max_length=100) 1019 authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all()) 1020 1021 The ``save()`` method 1022 ~~~~~~~~~~~~~~~~~~~~~ 1023 1024 Every form produced by ``form_for_model()`` also has a ``save()`` method. This 1025 method creates and saves a database object from the data bound to the form. For 1026 example:: 1027 1028 # Create a form instance from POST data. 1029 >>> f = ArticleForm(request.POST) 1030 1031 # Save a new Article object from the form's data. 1032 >>> new_article = f.save() 1033 1034 Note that ``save()`` will raise a ``ValueError`` if the data in the form 1035 doesn't validate -- i.e., ``if form.errors``. 1036 1037 Using an alternate base class 1038 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1039 1040 If you want to add custom methods to the form generated by 1041 ``form_for_model()``, write a class that extends ``django.newforms.BaseForm`` 1042 and contains your custom methods. Then, use the ``form`` argument to 1043 ``form_for_model()`` to tell it to use your custom form as its base class. 1044 For example:: 1045 1046 # Create the new base class. 1047 >>> class MyBase(BaseForm): 1048 ... def my_method(self): 1049 ... # Do whatever the method does 1050 1051 # Create the form class with a different base class. 1052 >>> ArticleForm = form_for_model(Article, form=MyBase) 1053 1054 # Instantiate the form. 1055 >>> f = ArticleForm() 1056 1057 # Use the base class method. 1058 >>> f.my_method() 1059 1060 Using a subset of fields on the form 1061 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1062 1063 **New in Django development version** 1064 1065 In some cases, you may not want all the model fields to appear on the generated 1066 form. There are two ways of telling ``form_for_model()`` to use only a subset 1067 of the model fields: 1068 1069 1. Set ``editable=False`` on the model field. As a result, *any* form 1070 created from the model via ``form_for_model()`` will not include that 1071 field. 1072 1073 2. Use the ``fields`` argument to ``form_for_model()``. This argument, if 1074 given, should be a list of field names to include in the form. 1075 1076 For example, if you want a form for the ``Author`` model (defined above) 1077 that includes only the ``name`` and ``title`` fields, you would specify 1078 ``fields`` like this:: 1079 1080 PartialArticleForm = form_for_model(Author, fields=('name', 'title')) 1081 1082 .. note:: 1083 1084 If you specify ``fields`` when creating a form with ``form_for_model()``, 1085 make sure that the fields that are *not* specified can provide default 1086 values, or are allowed to have a value of ``None``. If a field isn't 1087 specified on a form, the object created from the form can't provide 1088 a value for that attribute, which will prevent the new instance from 1089 being saved. 1090 1091 Overriding the default field types 1092 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1093 1094 The default field types, as described in the "Field types" table above, are 1095 sensible defaults; if you have a ``DateField`` in your model, chances are you'd 1096 want that to be represented as a ``DateField`` in your form. But 1097 ``form_for_model()`` gives you the flexibility of changing the form field type 1098 for a given model field. You do this by specifying a **formfield callback**. 1099 1100 A formfield callback is a function that, when provided with a model field, 1101 returns a form field instance. When constructing a form, ``form_for_model()`` 1102 asks the formfield callback to provide form field types. 1103 1104 By default, ``form_for_model()`` calls the ``formfield()`` method on the model 1105 field:: 1106 1107 def default_callback(field, **kwargs): 1108 return field.formfield(**kwargs) 1109 1110 The ``kwargs`` are any keyword arguments that might be passed to the form 1111 field, such as ``required=True`` or ``label='Foo'``. 1112 1113 For example, if you wanted to use ``MyDateFormField`` for any ``DateField`` 1114 field on the model, you could define the callback:: 1115 1116 >>> def my_callback(field, **kwargs): 1117 ... if isinstance(field, models.DateField): 1118 ... return MyDateFormField(**kwargs) 1119 ... else: 1120 ... return field.formfield(**kwargs) 1121 1122 >>> ArticleForm = form_for_model(formfield_callback=my_callback) 1123 1124 Note that your callback needs to handle *all* possible model field types, not 1125 just the ones that you want to behave differently to the default. That's why 1126 this example has an ``else`` clause that implements the default behavior. 1127 1128 Finding the model associated with a form 1129 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1130 1131 The model class that was used to construct the form is available 1132 using the ``_model`` property of the generated form:: 1133 1134 >>> ArticleForm = form_for_model(Article) 1135 >>> ArticleForm._model 1136 <class 'myapp.models.Article'> 1137 1138 ``form_for_instance()`` 1139 ----------------------- 1140 1141 ``form_for_instance()`` is like ``form_for_model()``, but it takes a model 1142 instance instead of a model class:: 1143 1144 # Create an Author. 1145 >>> a = Author(name='Joe Smith', title='MR', birth_date=None) 1146 >>> a.save() 1147 1148 # Create a form for this particular Author. 1149 >>> AuthorForm = form_for_instance(a) 1150 1151 # Instantiate the form. 1152 >>> f = AuthorForm() 1153 1154 When a form created by ``form_for_instance()`` is created, the initial 1155 data values for the form fields are drawn from the instance. However, 1156 this data is not bound to the form. You will need to bind data to the 1157 form before the form can be saved. 1158 1159 When you call ``save()`` on a form created by ``form_for_instance()``, 1160 the database instance will be updated. As in ``form_for_model()``, ``save()`` 1161 will raise ``ValueError`` if the data doesn't validate. 1162 1163 ``form_for_instance()`` has ``form``, ``fields`` and ``formfield_callback`` 1164 arguments that behave the same way as they do for ``form_for_model()``. 1165 1166 When should you use ``form_for_model()`` and ``form_for_instance()``? 1167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1168 1169 The ``form_for_model()`` and ``form_for_instance()`` functions are meant to be 1170 shortcuts for the common case. If you want to create a form whose fields map to 1171 more than one model, or a form that contains fields that *aren't* on a model, 1172 you shouldn't use these shortcuts. Creating a ``Form`` class the "long" way 1173 isn't that difficult, after all. 1174 873 1175 More coming soon 874 1176 ================ … … 881 1183 If you're really itching to learn and use this library, please be patient. 882 1184 We're working hard on finishing both the code and documentation. 883 884 Widgets885 =======django/branches/unicode/docs/templates_python.txt
r5185 r5214 718 718 tag_name, format_string = token.split_contents() 719 719 except ValueError: 720 raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents [0]720 raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] 721 721 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): 722 722 raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name … … 847 847 tag_name, date_to_be_formatted, format_string = token.split_contents() 848 848 except ValueError: 849 raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents [0]849 raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0] 850 850 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): 851 851 raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name … … 1081 1081 tag_name, arg = token.contents.split(None, 1) 1082 1082 except ValueError: 1083 raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents [0]1083 raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0] 1084 1084 m = re.search(r'(.*?) as (\w+)', arg) 1085 1085 if not m: django/branches/unicode/docs/testing.txt
r5185 r5214 178 178 * `Test Client`_ 179 179 * `TestCase`_ 180 * `E mail services`_180 * `E-mail services`_ 181 181 182 182 Test Client … … 460 460 461 461 At the start of each test case, in addition to installing fixtures, 462 Django clears the contents of the test e mail outbox.463 464 For more detail on e mail services during tests, see `Email services`_.462 Django clears the contents of the test e-mail outbox. 463 464 For more detail on e-mail services during tests, see `E-mail services`_. 465 465 466 466 Assertions … … 503 503 response. 504 504 505 E mail services505 E-mail services 506 506 -------------- 507 507 508 **New in Django development version** 508 509 509 If your view makes use of the `Django e mail services`_, you don't really510 want e mail to be sent every time you run a test using that view.510 If your view makes use of the `Django e-mail services`_, you don't really 511 want e-mail to be sent every time you run a test using that view. 511 512 512 513 When the Django test framework is initialized, it transparently replaces the 513 514 normal `SMTPConnection`_ class with a dummy implementation that redirects all 514 e mail to a dummy outbox. This outbox, stored as ``django.core.mail.outbox``,515 e-mail to a dummy outbox. This outbox, stored as ``django.core.mail.outbox``, 515 516 is a simple list of all `EmailMessage`_ instances that have been sent. 516 517 For example, during test conditions, it would be possible to run the following … … 542 543 mail.outbox = [] 543 544 544 .. _`Django e mail services`: ../email/545 .. _`Django e-mail services`: ../email/ 545 546 .. _`SMTPConnection`: ../email/#the-emailmessage-and-smtpconnection-classes 546 547 .. _`EmailMessage`: ../email/#the-emailmessage-and-smtpconnection-classes … … 670 671 ``teardown_test_environment()`` 671 672 Performs any global post-test teardown, such as removing the instrumentation 672 of the template rendering system and restoring normal e mail services.673 of the template rendering system and restoring normal e-mail services. 673 674 674 675 ``create_test_db(verbosity=1, autoclobber=False)`` django/branches/unicode/tests/modeltests/model_forms/models.py
r5126 r5214 180 180 </select><br /> Hold down "Control", or "Command" on a Mac, to select more than one.</td></tr> 181 181 182 You can restrict a form to a subset of the complete list of fields 183 by providing a 'fields' argument. If you try to save a 184 model created with such a form, you need to ensure that the fields 185 that are _not_ on the form have default values, or are allowed to have 186 a value of None. If a field isn't specified on a form, the object created 187 from the form can't provide a value for that field! 188 >>> PartialArticleForm = form_for_model(Article, fields=('headline','pub_date')) 189 >>> f = PartialArticleForm(auto_id=False) 190 >>> print f 191 <tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr> 192 <tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr> 193 182 194 You can pass a custom Form class to form_for_model. Make sure it's a 183 195 subclass of BaseForm, not Form. … … 225 237 <option value="3">Third test</option> 226 238 </select> Hold down "Control", or "Command" on a Mac, to select more than one.</li> 227 >>> f = TestArticleForm({'headline': u'New headline', 'pub_date': u'1988-01-04', 'writer': u'1', 'article': 'Hello.'}) 239 >>> f = TestArticleForm({'headline': u'Test headline', 'pub_date': u'1984-02-06', 'writer': u'1', 'article': 'Hello.'}) 240 >>> f.is_valid() 241 True 242 >>> test_art = f.save() 243 >>> test_art.id 244 1 245 >>> test_art = Article.objects.get(id=1) 246 >>> test_art.headline 247 u'Test headline' 248 249 You can create a form over a subset of the available fields 250 by specifying a 'fields' argument to form_for_instance. 251 >>> PartialArticleForm = form_for_instance(art, fields=('headline','pub_date')) 252 >>> f = PartialArticleForm({'headline': u'New headline', 'pub_date': u'1988-01-04'}, auto_id=False) 253 >>> print f.as_ul() 254 <li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li> 255 <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li> 228 256 >>> f.is_valid() 229 257 True django/branches/unicode/tests/regressiontests/forms/tests.py
r5126 r5214 2753 2753 <li>Password: <input type="password" name="password" /></li> 2754 2754 2755 # Callable initial data ######################################################## 2756 2757 The previous technique dealt with raw values as initial data, but it's also 2758 possible to specify callable data. 2759 2760 >>> class UserRegistration(Form): 2761 ... username = CharField(max_length=10) 2762 ... password = CharField(widget=PasswordInput) 2763 2764 We need to define functions that get called later. 2765 >>> def initial_django(): 2766 ... return 'django' 2767 >>> def initial_stephane(): 2768 ... return 'stephane' 2769 2770 Here, we're not submitting any data, so the initial value will be displayed. 2771 >>> p = UserRegistration(initial={'username': initial_django}, auto_id=False) 2772 >>> print p.as_ul() 2773 <li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> 2774 <li>Password: <input type="password" name="password" /></li> 2775 2776 The 'initial' parameter is meaningless if you pass data. 2777 >>> p = UserRegistration({}, initial={'username': initial_django}, auto_id=False) 2778 >>> print p.as_ul() 2779 <li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> 2780 <li><ul c
