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

时间:2017-09-05 21:34:47

标签: python django

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

如果是add,那么我正在显示表单字段file_upload,如果是change,那么我正在显示模型字段cnamemname < / p>

来自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视图,那么我将获得所有字段,即cname,mname,upload_file。

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

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以覆盖rep(c('aaa','bbb','ccc','ddd'),20) 中的add_viewchange_view方法:

ModelAdmin

答案 2 :(得分:0)

使用完全不同的形式添加/更改:

class couplingAdmin(admin.ModelAdmin):
    list_display = ('cname','mname')

    def get_form(self, request, obj=None, change=None, **kwargs):
        if not obj:
            # Use a different form only when adding a new record
            return CouplingUploadForm

        return super().get_form(request, obj=obj, change=change, **kwargs)