#12392: Create_object generic view does not provide a way to pre-populate a form
with dynamic data
-------------------------------------------------+--------------------------
Reporter: [email protected] | Owner: nobody
Status: closed | Milestone:
Component: Generic views | Version: SVN
Resolution: wontfix | Keywords:
pre-populate, generic, view, dictionary
Stage: Unreviewed | Has_patch: 0
Needs_docs: 0 | Needs_tests: 0
Needs_better_patch: 0 |
-------------------------------------------------+--------------------------
Changes (by lukeplant):
* status: reopened => closed
* resolution: => wontfix
Comment:
If you need the values to be dynamic based on the request object (which
you didn't mention before) you can do it by creating the model form in a
function that wraps the create_object view:
{{{
#!python
from django.forms import ModelForm
from myapp.models import MyModel
def my_view(request):
class MyModelForm(ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
kwargs['initial'] = {'field1': request.GET.get('field1','')}
return super(MyModelForm, self).__init__(*args, **kwargs)
return create_object(request, form_class=MyModelForm)
}}}
(If you haven't seen this before, it's called a closure -
`MyModelForm.__init__` is using the `request` object, which hasn't been
passed in to that method, but is available because it is in the enclosing
scope in which `MyModelForm.__init__` is defined. For each call to
`my_view`, a class called `MyModelForm` is created, and thrown away
afterwards.)
If you need to get values out of the request, you '''have''' to do this in
a view function that wraps create_object i.e. you cannot do it in the URL
conf. Unless, of course, we added a keyword argument to `create_object`
that is a callable that takes a request object and returns some values to
be passed to the form as 'initial', but this is only highlighting that we
are at the stage of very custom requirements that are best catered for
either by writing your own view completely or using something like the
code above. I'll admit that this isn't 'simple', but I wouldn't describe
your actual requirements as that simple either, and since there are so
many ways in which generic views could be customised we have to limit new
options to things that cannot be done in other ways (at least until class
based generic views arrive).
--
Ticket URL: <http://code.djangoproject.com/ticket/12392#comment:7>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.