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

ⅰ亾dé卋堺 提交于 2019-12-23 18:09:48

问题


I am trying to add an editable=False field to a custom admin form, but I am getting an error:

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

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

I added the readonly to admin.py, but still getting there error. Not sure what I am doing wrong here.


回答1:


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 :

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


来源:https://stackoverflow.com/questions/45699915/how-do-you-add-a-non-editable-field-to-a-custom-admin-form-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!