ThunderHorn
ThunderHorn

Reputation: 2035

Django make certain fields read-only for a certain element of a Model

My model looks like this:

class Article(models.Model):
    title = models.CharField(blank=False, null=False, max_length=200, verbose_name="title")
    description = RichTextUploadingField(blank=False, null=False, verbose_name="description")

Is it possible to:

1.

Create an article with a default title='Terms and conditions' which will be read-only in django-admin, but a description that can be modified in the django-admin?

2.

If I already have the article created, use the django shell to make the attribute read-only, like so?

python manage.py shell

from articles.models import Article
terms = Article.object.get(title='Terms and conditions')
terms.title.readonly = True

This option throws an error:

AttributeError: 'str' object has no attribute 'readonly'

Upvotes: 0

Views: 2166

Answers (2)

Marc Gouw
Marc Gouw

Reputation: 108

Looks like what you are looking for is the readonly_fields when defining the Admin Model. Check the Django docs on the ModelAdmin.readonly_fields attribute

In your case, define the following in admin.py:

from .models import Article

class ArticleAdmin(admin.ModelAdmin):
    readonly_fields=('title',)

admin.site.register(Article, ArticleAdmin)

Good luck!

Upvotes: 1

marcanuy
marcanuy

Reputation: 23972

You can do it in two steps:

  1. Make the field read only in the admin using Model.Admin.readonly_fields: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

  2. Use signals to fill the title before saving it, add a pre save hook where you set the default value of the title: https://docs.djangoproject.com/en/2.1/ref/signals/#pre-save

Upvotes: 1

Related Questions