[英]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.