【问题标题】:Different form fields for add and change view in Django admin在 Django admin 中添加和更改视图的不同表单字段
【发布时间】:2017-09-05 21:34:47
【问题描述】:

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

如果是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,我会得到所有字段,即cname、mname、upload_file。

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

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

【问题讨论】:

    标签: python django


    【解决方案1】:

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

    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)
    

    【讨论】:

    • change_view 仍然显示upload_file 字段。是不是因为我之前打过form = CouplingUploadForm
    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2011-01-15
        • 2015-10-19
        • 2017-02-24
        • 2011-10-04
        • 1970-01-01
        • 2012-02-25
        • 2016-08-11
        • 2014-08-23
        • 1970-01-01
        相关资源
        最近更新 更多