54

I'm trying to make all fields readonly without listing them explicitly.

Something like:

class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        return self.fields

The problem is CustomAdmin.fields is not set at this point.

Any ideas?

5

11 Answers 11

80

Since django 2.1, you can prevent editing, while allowing viewing, by returning False from the ModelAdmin's has_change_permission method, like this:

class CustomAdmin(admin.ModelAdmin):
    def has_change_permission(self, request, obj=None):
        return False

(This will not work before django 2.1, as it will also deny permission to any user trying only to view.)

4
  • 1
    Such a beautiful and nice solution. Why not more up-votes? Commented Oct 3, 2019 at 22:32
  • @ErikKalkoken: this works only since version 2.1 of django where the view permission was added. Before then (so up to and including django 2.0), the solution suggested by this answer will make the admin site deny permission to all users trying to view the relevant model in the admin. Agree that it's the neatest solution for recent django.
    – Jonathan
    Commented Dec 3, 2019 at 12:39
  • 2
    Great answer! For some applications, you might want to add has_delete_permission and has_add_permission methods too
    – andrewdotn
    Commented Jan 21, 2021 at 21:03
  • Not that inlines can't be added
    – krafter
    Commented Dec 19, 2021 at 13:17
45

Careful, self.model._meta.fields are not necessarily the same fields that CustomAdmin has!

"All fields of the Admin" would look more like this:

from django.contrib import admin
from django.contrib.admin.utils import flatten_fieldsets

class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if request.user.is_superuser:
            return self.readonly_fields

        if self.declared_fieldsets:
            return flatten_fieldsets(self.declared_fieldsets)
        else:
            return list(set(
                [field.name for field in self.opts.local_fields] +
                [field.name for field in self.opts.local_many_to_many]
            ))
8
  • Thanks this works great. Just had to remove the many_to_many because it makes it look weird (they're registered as inlines anyway and have their own permissions. This feels much safer then getting model._meta.
    – yprez
    Commented Dec 12, 2012 at 7:42
  • 1
    No worries. Careful if you ever have an m2m that's not an inline. Though it should make itself known :-) Commented Dec 12, 2012 at 10:20
  • Thank you. This is the most reasonable answer I found.
    – Greg Wang
    Commented Mar 17, 2014 at 4:28
  • 6
    declared_fieldsets is deprecated since django 1.7 and will be removed in django 1.9; replacing it with get_fieldsets(req,obj) reaches recursion limit. also, admin.util is renamed to admin.utils Commented May 7, 2015 at 9:28
  • 2
    This worked for me with Django 1.10 ` def get_readonly_fields(self, request, obj=None): if request.user.is_superuser: return self.readonly_fields return list(set( [field.name for field in self.opts.local_fields] + [field.name for field in self.opts.local_many_to_many] ))` Commented Mar 18, 2017 at 17:16
27

Ok, now there's this:

class CustomAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        # ...

        return [f.name for f in self.model._meta.fields]

Still looking for a less ugly way.

4
  • Actually I found this elsewhere. And after upvoting your answer and adjusting it a bit to the version I used and tested in my code posted my own.
    – yprez
    Commented Dec 11, 2012 at 10:23
  • the if clause doesn't add anything to your question Commented Dec 11, 2012 at 10:24
  • 1
    True. It's just cleaner. Also, it doesn't do this: AttributeError: type object 'NoneType' has no attribute '_meta' when creating objects.
    – yprez
    Commented Dec 11, 2012 at 10:27
  • This does not include any extra fields (eg: with a custom form).
    – WhyNotHugo
    Commented Jan 12, 2018 at 16:38
12

You could iterate through the model meta fields:

def get_readonly_fields(self, request, obj=None):
    if obj:
        self.readonly_fields = [field.name for field in obj.__class__._meta.fields]
    return self.readonly_fields
5
  • 2
    When user try to create new object you have exception here: obj.__class__._meta.fields Commented Dec 11, 2012 at 10:24
  • Ok, i delete my answer, you really was first :) Commented Dec 11, 2012 at 10:32
  • 3
    @hedde you aren't entitled to the answer just because you wrote it first, and just because someone has the same approach doesn't mean they are copying you or deserve a downvote Commented Dec 11, 2012 at 11:29
  • Really appreciated. Nice answer !! Commented Aug 19, 2017 at 12:00
  • This does not include any extra fields (eg: with a custom form).
    – WhyNotHugo
    Commented Jan 12, 2018 at 16:39
6

For Inlines (Tab or Stack)

def get_readonly_fields(self, request, obj=None):
    fields = []
    for field in self.model._meta.get_all_field_names():
        if field != 'id':
            fields.append(field)
    return fields

def has_add_permission(self, request):
    return False
2
  • return [field for field in self.model._meta.get_all_field_names() if field != 'id'] ### thanks YPREZ Commented Feb 28, 2018 at 7:47
  • 2
    The self.model._meta.get_all_field_names() methodology has been deprecated in Django 1.10+: docs.djangoproject.com/en/2.1/ref/models/meta/…
    – user535883
    Commented Dec 23, 2019 at 14:25
5

If someone still lookign for better way, you can use it like this:

@admin.register(ClassName)
class ClassNameAdmin(admin.ModelAdmin):
    readonly_fields = [field.name for field in ClassName._meta.fields]

ClassName is your Model class.

1
  • 1
    Thank you for coming back and posting this!
    – blakev
    Commented Feb 17, 2022 at 19:41
4

This worked for me with Django 1.10

def get_readonly_fields(self, request, obj=None):
    if request.user.is_superuser:
        return self.readonly_fields

    return list(set(
        [field.name for field in self.opts.local_fields] +
        [field.name for field in self.opts.local_many_to_many]
    ))
0

My requirement was similar . I needed only one field to be shown as read-only . And this worked fine:

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 1
    fields = ['choice_text', 'votes']
    readonly_fields = ['votes']

class QuestionAdmin(admin.ModelAdmin):
    #fields = ['pub_date', 'question_text']
    fieldsets = [
        (None, {'fields': ['question_text']}),
        ('Date Information', {'fields': ['pub_date']}),
    ]
    search_fields = ['question_text']


    inlines = [ChoiceInline]

Refer: C:\Python27\Lib\site-packages\django\contrib\admin\options.py

0

Say you have defined user_mode as;

Admin, Customers and Staff

If you'd like to deny a staff (and of course, customers) the privilege of deleting a customer, product, order etc...

Your code goes;

def get_readonly_fields(self, request: HttpRequest, obj=None):
    if request.user.user_mode != "Admin":
        return self.readonly_fields + ['user_mode']
    return super().get_readonly_fields(request, obj)

where user_mode = a model field holding the type of user.

N.B: my code uses "Pylance" (like typescript in JS)

-1

With get_fieldsets you get all fields from the form

def get_readonly_fields(self, request, obj=None):
    readonly = []
    for fs in self.get_fieldsets(request, obj):
        if len(fs) > 1:
            readonly += fs[1].get('fields', [])
    return readonly
1
  • calling get_fieldsets() inside get_readonly_fields() reaches recursion limit :( Commented May 7, 2015 at 9:31
-1
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
    ...
    readonly_fields = ["father", "mother", "spouse"]

reference : https://books.agiliq.com/projects/django-admin-cookbook/en/latest/changeview_readonly.html

1
  • Question was to get all fields readonly without listing them explicitly. Your answer suggest listing them explicitly. Commented Mar 14, 2020 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.