Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly models in Django admin interface?

How can I make a model completely read-only in the admin interface? It's for a kind of log table, where I'm using the admin features to search, sort, filter etc, but there is no need to modify the log.

In case this looks like a duplicate, here's not what I'm trying to do:

  • I'm not looking for readonly fields (even making every field readonly would still let you create new records)
  • I'm not looking to create a readonly user: every user should be readonly.
like image 463
Steve Bennett Avatar asked Nov 25 '11 06:11

Steve Bennett


People also ask

How do I restrict access to admin pages in Django?

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .

How do I give permission to admin in Django?

Test the 'view' permission is added to all modelsUsing #3 for Django 1.7 only creates the permission objects if the model doesn't already exist. Is there a way to create a migration (or something else) to create the permission objects for existing models?

What is model admin in Django?

It is used to create the form presented on both the add/change pages. You can easily provide your own ModelForm to override any default form behavior on the add/change pages. Alternatively, you can customize the default form rather than specifying an entirely new one by using the ModelAdmin. get_form() method.


1 Answers

The admin is for editing, not just viewing (you won't find a "view" permission). In order to achieve what you want you'll have to forbid adding, deleting, and make all fields readonly:

class MyAdmin(ModelAdmin):      def has_add_permission(self, request, obj=None):         return False      def has_delete_permission(self, request, obj=None):         return False 

(if you forbid changing you won't even get to see the objects)

For some untested code that tries to automate setting all fields read-only see my answer to Whole model as read-only

EDIT: also untested but just had a look at my LogEntryAdmin and it has

readonly_fields = MyModel._meta.get_all_field_names() 

Don't know if that will work in all cases.

EDIT: QuerySet.delete() may still bulk delete objects. To get around this, provide your own "objects" manager and corresponding QuerySet subclass which doesn't delete - see Overriding QuerySet.delete() in Django

like image 200
Danny W. Adair Avatar answered Oct 07 '22 19:10

Danny W. Adair