构建一个两阶段的Django管理表单以添加对象? [英] Build a two-stage Django admin form for adding an object?
问题描述
是否可以在Django admin中构建用于创建对象的两阶段表单?
Is it possible to build a two-stage form for creating an object in Django admin?
当管理员用户访问 / admin / my-app / article / add /
,我想显示一些选项。然后,该应用程序将基于创建的选择显示创建页面,其中包含预先计算的字段。
When an admin user visits /admin/my-app/article/add/
, I'd like to display some options. Then, the app would display the creation page with pre-calculated fields based on the selections made.
推荐答案
您可以在<$ c $上覆盖 add_view
方法c> ModelAdmin (来源)的 myapp.article
。它负责呈现模型形式并将对象添加到数据库。
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.
草稿
def add_view(self, request, **kwargs):
if Stage1:
do_my_stuff()
return response
else:
return super(ModelAdmin, self).add_view(self, request, **kwargs)
现在您需要区分两个阶段。 GET查询字符串中的参数可以做到这一点。要将初始数据传递给管理员中的表单,只需在查询字符串中包含字段名称值对作为参数。
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.
草稿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)
您可能需要查看代码以在您的请求中返回正确的响应第一阶段。有几个模板变量 add_view
设置,但希望这是一个很好的开始。
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.
这篇关于构建一个两阶段的Django管理表单以添加对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!