Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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 am still getting the error. What am I doing wrong?

like image 879
tryin2code Avatar asked Aug 15 '17 19:08

tryin2code


People also ask

How do you make a field non editable in Django admin?

editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form.

How do you make a field required in Django admin?

Making Fields Required In Django Admin In order to make the summary field required, we need to create a custom form for the Post model. I am making them on the same file you can do this on a separate forms.py file as well.

How do I override a form in Django?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class.

How do you make a field not required in Django?

Just add blank=True in your model field and it won't be required when you're using modelforms . "If the model field has blank=True , then required is set to False on the form field. Otherwise, required=True ."


1 Answers

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
like image 164
PRMoureu Avatar answered Sep 27 '22 18:09

PRMoureu