Python Django admin中添加和更改视图的不同表单字段

Python Django admin中添加和更改视图的不同表单字段,python,django,Python,Django,我想在Django admin中为添加和更改视图显示不同的表单字段 如果是add,则显示表单字段file\u upload;如果是change,则显示模型字段cname和mname 来自admin.py的代码 class couplingAdmin(admin.ModelAdmin): list_display = ('cname','mname') form = CouplingUploadForm #upload_file is here def get_form(

我想在Django admin中为添加和更改视图显示不同的表单字段

如果是
add
,则显示表单字段
file\u upload
;如果是
change
,则显示模型字段
cname
mname

来自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\u file

请建议如何从“管理”中的“更改”视图中删除
upload\u文件

非常感谢您的帮助。提前感谢。

您可以覆盖
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)

要使用完全不同的表单添加/更改,请执行以下操作:

类耦合管理员(admin.ModelAdmin):
列表显示=('cname','mname')
def get_表单(自我、请求、obj=None、更改=None、**kwargs):
如果不是obj:
#仅在添加新记录时使用其他表单
回程联轴节
return super().get_表单(请求,obj=obj,change=change,**kwargs)

更改视图仍显示
上载文件
字段。是不是因为我以前叫过
form=CouplingUploadForm
class couplingAdmin(admin.ModelAdmin):
    list_display = ('cname','mname')
    def get_fields(self, request, obj=None):
        if obj:
            fields=('upload_file',)
        else:
            fields =('cname','mname')
        return fields