0

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'

Community
  • 1
  • 1
ThunderHorn
  • 1,975
  • 1
  • 20
  • 42

2 Answers2

1

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

marcanuy
  • 23,118
  • 9
  • 64
  • 113
1

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!

Marc Gouw
  • 108
  • 4
  • can we bound it in a condition? Means I want to make a field readonly for selected objects. Is that possible with some django tweak? – brainLoop Feb 20 '19 at 09:22
  • Hi @brainLoop. I think you might want to add this as a new question, as your case is different than the question being asked here. That being said: I suppose you could define two `ModelAdmin` classes, one with the `readonly_fields` set, and another without. Check [this SO post](https://stackoverflow.com/questions/2223375/multiple-modeladmins-views-for-same-model-in-django-admin) on how to define multiple `ModelAdmins` for a single `Model`. A bit of a workaround, and I'm not even sure if it will work, but its the best suggestion I can come up with :-) – Marc Gouw Feb 21 '19 at 10:42