gpt4 book ai didi

Django 管理员 : Prefill data when clicking the add-another button next to a ForeignKey dropdown

转载 作者:行者123 更新时间:2023-12-02 09:54:00 24 4
gpt4 key购买 nike

在Django Admin中,当你修改一个对象的属性时,如果有一个ForeignKey,它会出现一个包含所有选择的下拉框,并加上一个“+”按钮来添加更多选择。当我点击它时,我想预填充一些数据。

我注意到如果我可以修改 URL,我就可以做到这一点(例如:http://localhost:8000/admin/app/model/add/?field=value 其中 fieldvalue 以编程方式修改。)

我认为我必须覆盖 admin.ModelAdmin 使用的 forms.ModelForm 中的某些内容,但我不确定是什么。

最佳答案

Django 允许您替换请求的 GET 字典(它用于预填充管理表单)。

如果您在 URL 中发送模型表单的字段值,Django 将自动填充 URL GET 参数中的值。

例如,考虑到“http://myhost/admin/app/model/add/?name=testname”,它将在管理添加 View 中预填充表单的name字段值为 'testname' 的模板。

但是,如果您要在 URL 中发送任何 ID,则需要通过覆盖 add_view 函数来修改 GET 参数。

摘自stackoverflow答案

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)

这只是一个例子。用你的模型和字段来做它:)

关于Django 管理员 : Prefill data when clicking the add-another button next to a ForeignKey dropdown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21272712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com