Build a two-stage Django admin form for adding an object?
Is it possible to build a two-stage form for creating an object in Django admin?
When an admin user visits /admin/my-app/article/add/
, I'd like to display some options. Then, the app would display the crea开发者_高级运维tion page with pre-calculated fields based on the selections made.
You could overwrite the add_view
method on the ModelAdmin
(Source) of myapp.article
. It is responsible for rendering the modelform and adding objects to the database.
While adding your functionality, you likely want to keep the original code intact instead of copying/modifying it.
Draft
def add_view(self, request, **kwargs):
if Stage1:
do_my_stuff()
return response
else:
return super(ModelAdmin, self).add_view(self, request, **kwargs)
Now you need to distinguish between the two stages. A parameter in the GET query string could do that. To pass initial data to a form in the admin, you only need to include the fieldname value pairs as parameters in the querystring.
Draft 2
def add_view(self, request, **kwargs):
if 'stage2' not in request.GET:
if request.method == 'POST':
# calculate values
parameters = 'field1=foo&field2=bar'
return redirect('myapp_article_add' + '?stage2=1&' + parameters)
else:
# prepare form for selections
return response
else:
return super(ModelAdmin, self).add_view(self, request, **kwargs)
You probably need to look at the code to return a correct response in your first stage. There are a couple of template variables add_view
sets, but hopefully this is a good start to look further.
精彩评论