Make django model field read-only or disable administrator when first saving object

I want to disable several fields from a model in django admin when saving initially.

"<input type="text" id="disabledTextInput" class="form-control" placeholder="Disabled input">" 

like this.

My model:

 class Blogmodel(models.Model): tag = models.ForeignKey(Tag) headline = models.CharField(max_length=255) image=models.ImageField(upload_to=get_photo_storage_path, null=True, blank=False) body_text = models.TextField() pub_date = models.DateField() authors = models.ForeignKey(Author) n_comments = models.IntegerField() 

I want to disable the "header" and "n_comments". I tried it in the admin.py file, but did not disable the fields on initial save. But for editing the fields of his work, he makes the fields read-only.

in admin.py

 class ItemAdmin(admin.ModelAdmin): exclude=("headline ",) def get_readonly_fields(self, request, obj=None): if obj: return ['headline '] else: return [] 

The header display is disabled, but only for editing. I want to disable it while creating an object. those. save first. can anyone direct me to this?

+6
source share
3 answers

If you want to make the field read-only at creation time, you should do it the other way around:

 def get_readonly_fields(self, request, obj=None): if obj is None: return ['headline '] return [] 
+4
source

There is no need to override get_readonly_fields . The simplest solution:

 class ItemAdmin(admin.ModelAdmin): exclude=("headline ",) readonly_fields=('headline', ) 

When using readonly_fields you cannot override get_readonly_fields because the default implementation reads the readonly_fields variable. Therefore, redefine this only if you have some kind of logic when choosing which field should be read-only.

+28
source

To disable it while saving the original object and for editing, we can do this

 class ItemAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj is None: return ['headline'] else: return ['headline'] return [] 

it worked for me.

+1
source

Source: https://habr.com/ru/post/981864/


All Articles