Reputation: 2035
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:
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?
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
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
Reputation: 23972
You can do it in two steps:
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
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