我正在尝试向自定义管理表单添加editable = False字段,但是我收到错误:
django.core.exceptions.FieldError: 'help_num' cannot be specified for
Investigation model form as it is a non-editable field
这是真的,在我的模型中,我将它设置为:
models.py
help_num = models.CharField(max_length=17, unique=True, default=increment_helpdesk_number, editable=False)
forms.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
我将readonly添加到admin.py,但仍然出现错误。不知道我在这里做错了什么。
答案 0 :(得分:4)
您需要从类表单字段列表中删除不可编辑的字段:
class HelpDeskModelForm(forms.ModelForm):
class Meta:
model = HelpDesk
fields = [
#"help_num",
"help_types",
...
"help_summary"
]
并像你一样保留ModelAdmin中的只读字段:
class HelpDeskModelAdmin(admin.ModelAdmin):
readonly_fields=('help_num',)
form = HelpDeskModelForm