Code

Ticket #6939: modeladmin_initial_parameters.diff

File modeladmin_initial_parameters.diff, 1.8 KB (added by Matthias Pronk <django@…>, 6 years ago)
Line 
1Index: django/newforms/models.py
2===================================================================
3--- django/newforms/models.py   (revision 7396)
4+++ django/newforms/models.py   (working copy)
5@@ -7,7 +7,7 @@
6 
7 from django.utils.translation import ugettext_lazy as _
8 from django.utils.encoding import smart_unicode
9-from django.utils.datastructures import SortedDict
10+from django.utils.datastructures import SortedDict, MultiValueDict
11 from django.core.exceptions import ImproperlyConfigured
12 
13 from util import ValidationError, ErrorList
14@@ -254,6 +254,9 @@
15             object_data = model_to_dict(instance, opts.fields, opts.exclude)
16         # if initial was provided, it should override the values from instance
17         if initial is not None:
18+            # If initial is an instance of MultiValueDict (or QueryDict), "flatten" it
19+            if isinstance(initial, MultiValueDict):
20+                initial = dict(initial.items())
21             object_data.update(initial)
22         BaseForm.__init__(self, data, files, auto_id, prefix, object_data, error_class, label_suffix)
23 
24Index: tests/modeltests/model_forms/models.py
25===================================================================
26--- tests/modeltests/model_forms/models.py      (revision 7396)
27+++ tests/modeltests/model_forms/models.py      (working copy)
28@@ -596,6 +596,15 @@
29 <option value="4">Fourth</option>
30 </select>  Hold down "Control", or "Command" on a Mac, to select more than one.</li>
31 
32+Use request data to initialize a form:
33+>>> class ArticleForm(ModelForm):
34+...     class Meta:
35+...         model = Article
36+>>> from django.http import QueryDict
37+>>> f = ArticleForm(initial=QueryDict('writer=3'))
38+>>> f.initial
39+{u'writer': u'3'}
40+
41 # ModelChoiceField ############################################################
42 
43 >>> from django.newforms import ModelChoiceField, ModelMultipleChoiceField