From 2e148d70647bfab640ab395fc98ba9492d061dad Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Tue, 9 Jan 2007 04:39:44 +0000 Subject: newforms: Added 'initial' parameter to Form, which lets initial data be specified dynamically git-svn-id: http://code.djangoproject.com/svn/django/trunk@4297 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/newforms.txt | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'docs') diff --git a/docs/newforms.txt b/docs/newforms.txt index 0b432e1b36..b4da35ecd4 100644 --- a/docs/newforms.txt +++ b/docs/newforms.txt @@ -721,6 +721,53 @@ validation if a particular field's value is not given. ``initial`` values are The ``widget`` argument lets you specify a ``Widget`` class to use when rendering this ``Field``. See _`Widgets` below for more information. +Dynamic initial values +---------------------- + +The ``initial`` argument to ``Field`` (explained above) lets you hard-code the +initial value for a ``Field`` -- but what if you want to declare the initial +value at runtime? For example, you might want to fill in a ``username`` field +with the username of the current session. + +To accomplish this, use the ``initial`` argument to a ``Form``. This argument, +if given, should be a dictionary mapping field names to initial values. Only +include the fields for which you're specifying an initial value; it's not +necessary to include every field in your form. For example:: + + >>> class CommentForm(forms.Form): + ... name = forms.CharField() + ... url = forms.URLField() + ... comment = forms.CharField() + >>> f = CommentForm(initial={'name': 'your username'}, auto_id=False) + >>> print f + Name: + Url: + Comment: + >>> f = CommentForm(initial={'name': 'another username'}, auto_id=False) + >>> print f + Name: + Url: + Comment: + +Just like the ``initial`` parameter to ``Field``, these values are only +displayed for unbound forms, and they're not used as fallback values if a +particular value isn't provided. + +Finally, note that if a ``Field`` defines ``initial`` *and* you include +``initial`` when instantiating the ``Form``, then the latter ``initial`` will +have precedence. In this example, ``initial`` is provided both at the field +level and at the form instance level, and the latter gets precedence:: + + >>> class CommentForm(forms.Form): + ... name = forms.CharField(initial='class') + ... url = forms.URLField() + ... comment = forms.CharField() + >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False) + >>> print f + Name: + Url: + Comment: + More coming soon ================ -- cgit v1.3