Django管理员:如何从GET变量填充一个新对象? [英] Django admin: How to populate a new object from GET variables?
问题描述
在Django的管理员中,我已经看到了如何使用GET变量设置添加对象表单的字段(例如 / admin / app / model / add?title = lol
将'标题'字段设置为'lol')。
In Django's admin, I've seen how I can set the fields of an 'add object' form using GET variables (e.g. /admin/app/model/add?title=lol
sets the 'Title' field to 'lol').
但是,我想要能够按照 / admin / app / model / add?key = 18
并从另一个模型的实例加载我的字段的默认数据。理想情况下,我也希望能够对我填写表单的值进行一些处理。我该怎么做?
However, I want to be able to do something along the lines of /admin/app/model/add?key=18
and load default data for my fields from an instance of another model. Ideally, I'd also like to be able to do some processing on the values that I populate the form with. How do I do this?
推荐答案
我设法弄清楚了。覆盖整个 add_view
方法似乎对我来说太过分了。幸运的是,Django允许您替换请求
的 GET
dict(它用于预先填充管理表单)。以下为我工作:
I managed to figure it out. Overriding the entire add_view
method seemed like too much clutter to me. Thankfully, Django allows you to replace a request
's GET
dict (which it uses to pre-populate the admin form). The following worked for me:
class ArticleAdmin(admin.ModelAdmin):
// ...
def add_view(self, request, form_url='', extra_context=None):
source_id = request.GET.get('source',None)
if source_id != None:
source = FeedPost.objects.get(id=source_id)
// any extra processing can go here...
g = request.GET.copy()
g.update({
'title':source.title,
'contents':source.description + u"... \n\n[" + source.url + "]",
})
request.GET = g
return super(ArticleAdmin, self).add_view(request, form_url, extra_context)
这样,我从URL中的一个参数中获取'source'对象,加载我需要的值,做我想要的他们,并预先填写表单。
This way, I obtain the 'source' object from a parameter in the URL, load the values I need from it, do what I want with them, and pre-populate the form.
这篇关于Django管理员:如何从GET变量填充一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!