Django

Code

Changeset 5214

Show
Ignore:
Timestamp:
05/13/07 01:23:30 (2 years ago)
Author:
mtredinnick
Message:

unicode: Merged from trunk up to [5213].

Files:

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  
    7979    Jure Cuhalev <gandalf@owca.info> 
    8080    dackze+django@gmail.com 
     81    David Danier <goliath.mailinglist@gmx.de> 
    8182    Dirk Datzert <dummy@habmalnefrage.de> 
    8283    Jonathan Daugherty (cygnus) <http://www.cprogrammer.org/> 
  • django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/djangojs.po

    r3827 r5214  
    4747#: contrib/admin/media/js/calendar.js:24 
    4848msgid "January February March April May June July August September October November December" 
    49 msgstr "一月 二月 三月 四月 五月 六月 六月 七月 八月 九月 十月 十一月 十二月" 
     49msgstr "一月 二月 三月 四月 五月 六月 七月 八月 九月 十月 十一月 十二月" 
    5050 
    5151#: contrib/admin/media/js/dateparse.js:33 
  • django/branches/unicode/django/conf/locale/zh_CN/LC_MESSAGES/django.po

    r3827 r5214  
    13451345#: utils/dates.py:19 
    13461346msgid "may" 
    1347 msgstr "月" 
     1347msgstr "月" 
    13481348 
    13491349#: utils/dates.py:19 
  • django/branches/unicode/django/contrib/localflavor/is_/forms.py

    r5126 r5214  
    4242        """ 
    4343        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 == 0 
     44        return sum([int(value[i]) * check[i] for i in range(10)]) % 11 == 0 
    4545 
    4646    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  
    6060    c = len(word_list) 
    6161    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) 
    6467    else: 
    6568        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  
    234234                output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 
    235235                    (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))), 
    237237                    style.SQL_KEYWORD('SELECT'), 
    238238                    style.SQL_FIELD(quote_name(f.column)), 
     
    243243            output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 
    244244                (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())), 
    246246                style.SQL_KEYWORD('SELECT'), 
    247247                style.SQL_FIELD(quote_name('id')), 
  • django/branches/unicode/django/db/backends/postgresql_psycopg2/base.py

    r5081 r5214  
    185185                output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 
    186186                    (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))), 
    188188                    style.SQL_KEYWORD('SELECT'), 
    189189                    style.SQL_FIELD(quote_name(f.column)), 
     
    194194            output.append("%s setval('%s', (%s max(%s) %s %s));" % \ 
    195195                (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())), 
    197197                style.SQL_KEYWORD('SELECT'), 
    198198                style.SQL_FIELD(quote_name('id')), 
  • django/branches/unicode/django/http/__init__.py

    r5197 r5214  
    109109        MultiValueDict.__setitem__(self, key, value) 
    110110 
     111    def __delitem__(self, key): 
     112        self._assert_mutable() 
     113        super(QueryDict, self).__delitem__(key) 
     114 
    111115    def get(self, key, default=None): 
    112116        return str_to_unicode(MultiValueDict.get(self, key, default), self.encoding) 
  • django/branches/unicode/django/newforms/forms.py

    r5126 r5214  
    256256        if not self.form.is_bound: 
    257257            data = self.form.initial.get(self.name, self.field.initial) 
     258            if callable(data): 
     259                data = data() 
    258260        else: 
    259261            data = self.data 
  • django/branches/unicode/django/newforms/models.py

    r4878 r5214  
    1313           'ModelChoiceField', 'ModelMultipleChoiceField') 
    1414 
    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): 
     15def save_instance(form, instance, fields=None, fail_message='saved', commit=True): 
    2616    """ 
    2717    Saves bound Form ``form``'s clean_data into model instance ``instance``. 
     
    3424    opts = instance.__class__._meta 
    3525    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)
    3727    clean_data = form.clean_data 
    3828    for f in opts.fields: 
    3929        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: 
    4032            continue 
    4133        setattr(instance, f.name, clean_data[f.name]) 
     
    4335        instance.save() 
    4436        for f in opts.many_to_many: 
     37            if fields and f.name not in fields: 
     38                continue 
    4539            if f.name in clean_data: 
    4640                setattr(instance, f.attname, clean_data[f.name]) 
     
    5145    return instance 
    5246 
    53 def make_instance_save(instance): 
    54     "Returns the save() method for a form_for_instance Form." 
     47def make_model_save(model, fields, fail_message): 
     48    "Returns the save() method for a Form." 
    5549    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     
     53def 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) 
    5757    return save 
    5858 
    59 def form_for_model(model, form=BaseForm, formfield_callback=lambda f: f.formfield()): 
     59def form_for_model(model, form=BaseForm, fields=None, formfield_callback=lambda f: f.formfield()): 
    6060    """ 
    6161    Returns a Form class for the given Django model class. 
     
    7272        if not f.editable: 
    7373            continue 
     74        if fields and not f.name in fields: 
     75            continue 
    7476        formfield = formfield_callback(f) 
    7577        if formfield: 
    7678            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')}) 
    7982 
    80 def form_for_instance(instance, form=BaseForm, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 
     83def form_for_instance(instance, form=BaseForm, fields=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)): 
    8184    """ 
    8285    Returns a Form class for the given Django model instance. 
     
    9598        if not f.editable: 
    9699            continue 
     100        if fields and not f.name in fields: 
     101            continue 
    97102        current_value = f.value_from_object(instance) 
    98103        formfield = formfield_callback(f, initial=current_value) 
    99104        if formfield: 
    100105            field_list.append((f.name, formfield)) 
    101     fields = SortedDictFromList(field_list) 
     106    base_fields = SortedDictFromList(field_list) 
    102107    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')}) 
    104109 
    105110def form_for_fields(field_list): 
  • django/branches/unicode/django/test/testcases.py

    r5185 r5214  
    11import re, doctest, unittest 
     2import sys 
    23from urlparse import urlparse 
    34from django.db import transaction 
     
    4647            management.load_data(self.fixtures, verbosity=0) 
    4748        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 call  
    52         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(). 
    5455        """ 
    5556        self.client = Client() 
    5657        self._pre_setup() 
    57         super(TestCase, self).run(result) 
     58        super(TestCase, self).__call__(result) 
    5859 
    5960    def assertRedirects(self, response, expected_path, status_code=302, target_status_code=200): 
     
    109110                    if field: 
    110111                        if field in context[form].errors: 
    111                             self.assertTrue(err in context[form].errors[field],  
     112                            self.failUnless(err in context[form].errors[field],  
    112113                            "The field '%s' on form '%s' in context %d does not contain the error '%s' (actual errors: %s)" %  
    113114                                (field, form, i, err, list(context[form].errors[field]))) 
     
    118119                            self.fail("The form '%s' in context %d does not contain the field '%s'" % (form, i, field)) 
    119120                    else: 
    120                         self.assertTrue(err in context[form].non_field_errors(),  
     121                        self.failUnless(err in context[form].non_field_errors(),  
    121122                            "The form '%s' in context %d does not contain the non-field error '%s' (actual errors: %s)" %  
    122123                                (form, i, err, list(context[form].non_field_errors()))) 
     
    128129        if isinstance(response.template, list): 
    129130            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, 
    131132                u"Template '%s' was not one of the templates used to render the response. Templates used: %s" % 
    132133                    (template_name, u', '.join(template_names))) 
     
    141142        "Assert that the template with the provided name was NOT used in rendering the response" 
    142143        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], 
    144145                u"Template '%s' was used unexpectedly in rendering the response" % template_name) 
    145146        elif response.template: 
    146147            self.assertNotEqual(template_name, response.template.name, 
    147148                u"Template '%s' was used unexpectedly in rendering the response" % template_name) 
    148          
     149 
  • django/branches/unicode/docs/i18n.txt

    r5185 r5214  
    237237``{% endblocktrans %}``. Example:: 
    238238 
    239     {% blocktrans count list|count as counter %} 
     239    {% blocktrans count list|length as counter %} 
    240240    There is only one {{ name }} object. 
    241241    {% plural %} 
  • django/branches/unicode/docs/install.txt

    r5126 r5214  
    5757 
    5858  If you're on Windows, check out the unofficial `compiled Windows version`_. 
    59    
     59 
    6060* If you're using MySQL, you'll need MySQLdb_, version 1.2.1p2 or higher. 
    6161  You will also want to read the database-specific notes for the `MySQL backend`_. 
     
    7676================================= 
    7777 
    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.  
     78If you are upgrading your installation of Django from a previous version, 
     79you will need to uninstall the old Django version before installing the 
     80new version. 
    8181 
    8282If you installed Django using ``setup.py install``, uninstalling 
    83 is as simple as deleting the ``django`` directory from your Python  
     83is as simple as deleting the ``django`` directory from your Python 
    8484``site-packages``. 
    8585 
    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``.  
     86If you installed Django from a Python Egg, remove the Django ``.egg`` file, 
     87and remove the reference to the egg in the file named ``easy-install.pth``. 
    8888This file should also be located in your ``site-packages`` directory. 
    8989 
     
    9393    system, and the location in which Python was installed. However, the 
    9494    following locations are common: 
    95      
     95 
    9696    * If you're using Linux: ``/usr/lib/python2.X/site-packages`` 
    9797 
  • django/branches/unicode/docs/newforms.txt

    r4819 r5214  
    871871``help_text``). 
    872872 
     873Generating forms for models 
     874=========================== 
     875 
     876If you're building a database-driven app, chances are you'll have forms that 
     877map closely to Django models. For instance, you might have a ``BlogComment`` 
     878model, and you want to create a form that lets people submit comments. In this 
     879case, it would be redundant to define the field types in your form, because 
     880you've already defined the fields in your model. 
     881 
     882For 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 
     888The method ``django.newforms.form_for_model()`` creates a form based on the 
     889definition 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 
     892For 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 
     902It bears repeating that ``form_for_model()`` takes the model *class*, not a 
     903model instance, and it returns a ``Form`` *class*, not a ``Form`` instance. 
     904 
     905Field types 
     906~~~~~~~~~~~ 
     907 
     908The generated ``Form`` class will have a form field for every model field. Each 
     909model field has a corresponding default form field. For example, a 
     910``CharField`` on a model is represented as a ``CharField`` on a form. A 
     911model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is 
     912the 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 
     952As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field 
     953types 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 
     962In 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 
     977Finally, note that you can override the form field used for a given model 
     978field. See "Overriding the default field types" below. 
     979 
     980A full example 
     981~~~~~~~~~~~~~~ 
     982 
     983Consider 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 
     1005With these models, a call to ``form_for_model(Author)`` would return a ``Form`` 
     1006class 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 
     1014A call to ``form_for_model(Book)`` would return a ``Form`` class equivalent to 
     1015this:: 
     1016 
     1017    class BookForm(forms.Form): 
     1018        name = forms.CharField(max_length=100) 
     1019        authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all()) 
     1020 
     1021The ``save()`` method 
     1022~~~~~~~~~~~~~~~~~~~~~ 
     1023 
     1024Every form produced by ``form_for_model()`` also has a ``save()`` method. This 
     1025method creates and saves a database object from the data bound to the form. For 
     1026example:: 
     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 
     1034Note that ``save()`` will raise a ``ValueError`` if the data in the form 
     1035doesn't validate -- i.e., ``if form.errors``. 
     1036 
     1037Using an alternate base class 
     1038~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     1039 
     1040If you want to add custom methods to the form generated by 
     1041``form_for_model()``, write a class that extends ``django.newforms.BaseForm`` 
     1042and 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. 
     1044For 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 
     1060Using a subset of fields on the form 
     1061~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     1062 
     1063**New in Django development version** 
     1064 
     1065In some cases, you may not want all the model fields to appear on the generated 
     1066form. There are two ways of telling ``form_for_model()`` to use only a subset 
     1067of 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 
     1091Overriding the default field types 
     1092~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     1093 
     1094The default field types, as described in the "Field types" table above, are 
     1095sensible defaults; if you have a ``DateField`` in your model, chances are you'd 
     1096want 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 
     1098for a given model field. You do this by specifying a **formfield callback**. 
     1099 
     1100A formfield callback is a function that, when provided with a model field, 
     1101returns a form field instance. When constructing a form, ``form_for_model()`` 
     1102asks the formfield callback to provide form field types. 
     1103 
     1104By default, ``form_for_model()`` calls the ``formfield()`` method on the model 
     1105field:: 
     1106 
     1107    def default_callback(field, **kwargs): 
     1108        return field.formfield(**kwargs) 
     1109 
     1110The ``kwargs`` are any keyword arguments that might be passed to the form 
     1111field, such as ``required=True`` or ``label='Foo'``. 
     1112 
     1113For example, if you wanted to use ``MyDateFormField`` for any ``DateField`` 
     1114field 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 
     1124Note that your callback needs to handle *all* possible model field types, not 
     1125just the ones that you want to behave differently to the default. That's why 
     1126this example has an ``else`` clause that implements the default behavior. 
     1127 
     1128Finding the model associated with a form 
     1129~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     1130 
     1131The model class that was used to construct the form is available 
     1132using 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 
     1142instance 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 
     1154When a form created by ``form_for_instance()`` is created, the initial 
     1155data values for the form fields are drawn from the instance. However, 
     1156this data is not bound to the form. You will need to bind data to the 
     1157form before the form can be saved. 
     1158 
     1159When you call ``save()`` on a form created by ``form_for_instance()``, 
     1160the database instance will be updated. As in ``form_for_model()``, ``save()`` 
     1161will raise ``ValueError`` if the data doesn't validate. 
     1162 
     1163``form_for_instance()`` has ``form``, ``fields`` and ``formfield_callback`` 
     1164arguments that behave the same way as they do for ``form_for_model()``. 
     1165 
     1166When should you use ``form_for_model()`` and ``form_for_instance()``? 
     1167~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     1168 
     1169The ``form_for_model()`` and ``form_for_instance()`` functions are meant to be 
     1170shortcuts for the common case. If you want to create a form whose fields map to 
     1171more than one model, or a form that contains fields that *aren't* on a model, 
     1172you shouldn't use these shortcuts. Creating a ``Form`` class the "long" way 
     1173isn't that difficult, after all. 
     1174 
    8731175More coming soon 
    8741176================ 
     
    8811183If you're really itching to learn and use this library, please be patient. 
    8821184We're working hard on finishing both the code and documentation. 
    883  
    884 Widgets 
    885 ======= 
  • django/branches/unicode/docs/templates_python.txt

    r5185 r5214  
    718718            tag_name, format_string = token.split_contents() 
    719719        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] 
    721721        if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): 
    722722            raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name 
     
    847847            tag_name, date_to_be_formatted, format_string = token.split_contents() 
    848848        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] 
    850850        if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")): 
    851851            raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name 
     
    10811081            tag_name, arg = token.contents.split(None, 1) 
    10821082        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] 
    10841084        m = re.search(r'(.*?) as (\w+)', arg) 
    10851085        if not m: 
  • django/branches/unicode/docs/testing.txt

    r5185 r5214  
    178178* `Test Client`_ 
    179179* `TestCase`_ 
    180 * `Email services`_ 
     180* `E-mail services`_ 
    181181 
    182182Test Client 
     
    460460 
    461461At the start of each test case, in addition to installing fixtures, 
    462 Django clears the contents of the test email outbox. 
    463  
    464 For more detail on email services during tests, see `Email services`_. 
     462Django clears the contents of the test e-mail outbox. 
     463 
     464For more detail on e-mail services during tests, see `E-mail services`_. 
    465465 
    466466Assertions 
     
    503503    response. 
    504504 
    505 Email services 
     505E-mail services 
    506506-------------- 
     507 
    507508**New in Django development version** 
    508509 
    509 If your view makes use of the `Django email services`_, you don't really 
    510 want email to be sent every time you run a test using that view. 
     510If your view makes use of the `Django e-mail services`_, you don't really 
     511want e-mail to be sent every time you run a test using that view. 
    511512 
    512513When the Django test framework is initialized, it transparently replaces the 
    513514normal `SMTPConnection`_ class with a dummy implementation that redirects all 
    514 email to a dummy outbox. This outbox, stored as ``django.core.mail.outbox``, 
     515e-mail to a dummy outbox. This outbox, stored as ``django.core.mail.outbox``, 
    515516is a simple list of all `EmailMessage`_ instances that have been sent. 
    516517For example, during test conditions, it would be possible to run the following 
     
    542543    mail.outbox = [] 
    543544 
    544 .. _`Django email services`: ../email/ 
     545.. _`Django e-mail services`: ../email/ 
    545546.. _`SMTPConnection`: ../email/#the-emailmessage-and-smtpconnection-classes 
    546547.. _`EmailMessage`: ../email/#the-emailmessage-and-smtpconnection-classes 
     
    670671``teardown_test_environment()`` 
    671672    Performs any global post-test teardown, such as removing the instrumentation 
    672     of the template rendering system and restoring normal email services. 
     673    of the template rendering system and restoring normal e-mail services. 
    673674 
    674675``create_test_db(verbosity=1, autoclobber=False)`` 
  • django/branches/unicode/tests/modeltests/model_forms/models.py

    r5126 r5214  
    180180</select><br /> Hold down "Control", or "Command" on a Mac, to select more than one.</td></tr> 
    181181 
     182You can restrict a form to a subset of the complete list of fields 
     183by providing a 'fields' argument. If you try to save a 
     184model created with such a form, you need to ensure that the fields 
     185that are _not_ on the form have default values, or are allowed to have 
     186a value of None. If a field isn't specified on a form, the object created 
     187from 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 
    182194You can pass a custom Form class to form_for_model. Make sure it's a 
    183195subclass of BaseForm, not Form. 
     
    225237<option value="3">Third test</option> 
    226238</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() 
     241True 
     242>>> test_art = f.save() 
     243>>> test_art.id 
     244
     245>>> test_art = Article.objects.get(id=1) 
     246>>> test_art.headline 
     247u'Test headline' 
     248 
     249You can create a form over a subset of the available fields 
     250by 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> 
    228256>>> f.is_valid() 
    229257True 
  • django/branches/unicode/tests/regressiontests/forms/tests.py

    r5126 r5214  
    27532753<li>Password: <input type="password" name="password" /></li> 
    27542754 
     2755# Callable initial data ######################################################## 
     2756 
     2757The previous technique dealt with raw values as initial data, but it's also 
     2758possible to specify callable data. 
     2759 
     2760>>> class UserRegistration(Form): 
     2761...    username = CharField(max_length=10) 
     2762...    password = CharField(widget=PasswordInput) 
     2763 
     2764We need to define functions that get called later. 
     2765>>> def initial_django(): 
     2766...     return 'django' 
     2767>>> def initial_stephane(): 
     2768...     return 'stephane' 
     2769 
     2770Here, 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 
     2776The '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