Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make django model field read only or disable in admin while saving the object first time

I want to disable the few fields from model in django admin while saving initially.

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

like this.

My model is:

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 "headline" and "n_comments". i tried it in admin.py file, but its not disabling the fields on initial saving. But for editing the fields its working, it making 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 []

Headling getting disabled but for edit only. i want to disable it at the time of object creation. i.e. first save. can anyone guide me for this?

like image 536
Wagh Avatar asked Feb 02 '15 10:02

Wagh


People also ask

How do I make a field read-only in Django admin?

Django admin by default shows all fields as editable and this fields option will display its data as-is and non-editable. we use readonly_fields is used without defining explicit ordering through ModelAdmin or ModelAdmin. fieldsets they will be added. Now we make the Question text fields read-only.

How do you make a field Uneditable in Django?

The disabled boolean argument, when set to True , disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.

How do I override model save in Django?

Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField.


1 Answers

There is no need to override get_readonly_fields. Simplest solution would be:

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

When using readonly_fields you can't override get_readonly_fields, because default implementation reads readonly_fields variable. So overriding it only if you have to have some logic on deciding which field should be read-only at time.

like image 117
GwynBleidD Avatar answered Oct 06 '22 10:10

GwynBleidD