简体   繁体   English

如何在 Django 中向自定义管理表单添加不可编辑的字段

[英]How do you add a non-editable field to a custom admin form in Django

I am trying to add an editable=False field to a custom admin form, but I am getting an error:我正在尝试向自定义管理表单添加一个editable=False字段,但出现错误:

django.core.exceptions.FieldError: 'help_num' cannot be specified for 
Investigation model form as it is a non-editable field

This is true, in my model I have it set as such:这是真的,在我的模型中,我将其设置为:

models.py模型.py

help_num = models.CharField(max_length=17, unique=True, default=increment_helpdesk_number, editable=False)

forms.py表格.py

class HelpDeskModelForm(forms.ModelForm):

    class Meta:
      model = HelpDesk
      fields = [
          "help_num",
          "help_types",
           ...
          "help_summary"
          ]

admin.py管理文件

class HelpDeskModelAdmin(admin.ModelAdmin):
    readonly_fields=('help_num',)
    form = HelpDeskModelForm

I added the readonly to admin.py, but am still getting the error.我将readonly添加到 admin.py,但仍然出现错误。 What am I doing wrong?我做错了什么?

You need to remove the non-editable field from your class form list of fields :您需要从类表单字段列表中删除不可编辑的字段:

class HelpDeskModelForm(forms.ModelForm):

    class Meta:
      model = HelpDesk
      fields = [
          #"help_num",
          "help_types",
           ...
          "help_summary"
          ]

And keep the read-only fields in the ModelAdmin like you did :并像您一样在 ModelAdmin 中保留只读字段:

class HelpDeskModelAdmin(admin.ModelAdmin):
    readonly_fields=('help_num',)
    form = HelpDeskModelForm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建一个仅显示(不可编辑)Django 管理字段 - Creating a display-only (non-editable) Django admin field 如何在 django 管理员中创建“仅创建”不可编辑字段 - How to make a “create-only” non-editable field in django admin Django管理员,使用DateTime小部件在创建时设置了不可编辑的日期字段 - Django admin, setting a non-editable date field on creation with the DateTime widget Django:无法为订单模型表单指定“已创建”,因为它是不可编辑的字段 - Django: 'created' cannot be specified for Order model form as it is a non-editable field django.core.exceptions.FieldError:不能为论坛 model 表单指定“日期”,因为它是不可编辑的字段 - django.core.exceptions.FieldError: 'date' cannot be specified for Forum model form as it is a non-editable field 如何在模型类的Flask Admin视图中使字段不可编辑 - How to make a field non-editable in Flask Admin view of a model class (Django REST)覆盖(视图)`create` 方法中的不可编辑字段 - (Django REST) Override Non-Editable Field in the (Views) `create` Method 无法为文章模型表单指定“内容”,因为它是不可编辑的字段 - 'content' cannot be specified for Article model form as it is a non-editable field Django:如何在内联模型表单集中默认情况下使字段不可编辑? - Django: How do I make fields non-editable by default in an inline model formset? 如何在Django管理主页中添加自定义部分? - How do you add a custom section to the Django admin home page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM