gpt4 book ai didi

python - 在 Django 管理中添加和更改 View 的不同表单字段

转载 作者:行者123 更新时间:2023-11-28 22:24:50 25 4
gpt4 key购买 nike

我想在 Django 管理中显示不同的表单字段以添加和更改 View 。

如果是add,那么我会显示表单字段file_upload,如果是change,那么我会显示模型字段 cnamemname

来自 admin.py 的代码

class couplingAdmin(admin.ModelAdmin):
list_display = ('cname','mname')
form = CouplingUploadForm #upload_file is here

def get_form(self, request, obj=None, **kwargs):
# Proper kwargs are form, fields, exclude, formfield_callback
if obj: # obj is not None, so this is a change page
kwargs['exclude'] = ['upload_file',]
else: # obj is None, so this is an add page
kwargs['exclude'] = ['cname','mname',]
return super(couplingAdmin, self).get_form(request, obj, **kwargs)

如果是 add 就没问题,但如果是 change View ,那么我将获取所有字段,即 cname、mname、upload_file。

请建议我如何从管理员的更改 View 中删除 upload_file

非常感谢任何帮助。提前致谢。

最佳答案

您可以覆盖 add_viewchange_view ModelAdmin 中的方法:

class CouplingAdmin(admin.ModelAdmin):
list_display = ('cname', 'mname')
form = CouplingUploadForm # upload_file is here

def add_view(self, request, extra_content=None):
self.exclude = ('cname', 'mname')
return super(CouplingAdmin, self).add_view(request)

def change_view(self, request, object_id, extra_content=None):
self.exclude = ('upload_file',)
return super(CouplingAdmin, self).change_view(request, object_id)

关于python - 在 Django 管理中添加和更改 View 的不同表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46063686/

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