| 1 |
--- |
| 2 |
title: Admin |
| 3 |
description: How to use django-guardian with Django's admin interface. |
| 4 |
--- |
| 5 |
|
| 6 |
# Django Admin Integration |
| 7 |
|
| 8 |
Django comes with an excellent and widely used *Admin* application. |
| 9 |
Basically, it provides content management for Django applications. |
| 10 |
Users with access to admin panel can manage users, groups, permissions and |
| 11 |
other data provided by system. |
| 12 |
|
| 13 |
`django-guardian` comes with simple object permissions management |
| 14 |
integration for Django's admin application. |
| 15 |
|
| 16 |
## Usage |
| 17 |
|
| 18 |
It is easy to use admin integration. Simply use `GuardedModelAdmin` instead of standard |
| 19 |
`django.contrib.admin.ModelAdmin` class for registering models within |
| 20 |
the admin. In example, look at the following model: |
| 21 |
|
| 22 |
``` python |
| 23 |
from django.db import models |
| 24 |
|
| 25 |
|
| 26 |
class Post(models.Model): |
| 27 |
title = models.CharField('title', max_length=64) |
| 28 |
slug = models.SlugField(max_length=64) |
| 29 |
content = models.TextField('content') |
| 30 |
created_at = models.DateTimeField(auto_now_add=True, db_index=True) |
| 31 |
|
| 32 |
class Meta: |
| 33 |
permissions = ( |
| 34 |
('hide_post', 'Can hide post'), |
| 35 |
) |
| 36 |
get_latest_by = 'created_at' |
| 37 |
|
| 38 |
def __str__(self): |
| 39 |
return self.title |
| 40 |
|
| 41 |
def get_absolute_url(self): |
| 42 |
return {'post_slug': self.slug} |
| 43 |
``` |
| 44 |
|
| 45 |
We want to register `Post` model within admin application. Normally, we |
| 46 |
would do this as follows within `admin.py` file of our application: |
| 47 |
|
| 48 |
``` python |
| 49 |
from django.contrib import admin |
| 50 |
|
| 51 |
from posts.models import Post |
| 52 |
|
| 53 |
|
| 54 |
class PostAdmin(admin.ModelAdmin): |
| 55 |
prepopulated_fields = {"slug": ("title",)} |
| 56 |
list_display = ('title', 'slug', 'created_at') |
| 57 |
search_fields = ('title', 'content') |
| 58 |
ordering = ('-created_at',) |
| 59 |
date_hierarchy = 'created_at' |
| 60 |
|
| 61 |
admin.site.register(Post, PostAdmin) |
| 62 |
``` |
| 63 |
|
| 64 |
If we would like to add object permissions management for `Post` model |
| 65 |
we would need to change `PostAdmin` base class into `GuardedModelAdmin`. |
| 66 |
Our code could look as follows: |
| 67 |
|
| 68 |
``` python |
| 69 |
from django.contrib import admin |
| 70 |
|
| 71 |
from posts.models import Post |
| 72 |
|
| 73 |
from guardian.admin import GuardedModelAdmin |
| 74 |
|
| 75 |
|
| 76 |
class PostAdmin(GuardedModelAdmin): |
| 77 |
prepopulated_fields = {"slug": ("title",)} |
| 78 |
list_display = ('title', 'slug', 'created_at') |
| 79 |
search_fields = ('title', 'content') |
| 80 |
ordering = ('-created_at',) |
| 81 |
date_hierarchy = 'created_at' |
| 82 |
|
| 83 |
admin.site.register(Post, PostAdmin) |
| 84 |
``` |
| 85 |
|
| 86 |
And thats it. We can now navigate to **change** post page and just next |
| 87 |
to the *history* link we can click *Object permissions* button to manage |
| 88 |
row level permissions. |
| 89 |
|
| 90 |
!!! note |
| 91 |
Example above is shipped with `django-guardian` package with the example project. |
| 92 |
|
| 93 |
## Restricting Access to the Object Permissions Views |
| 94 |
|
| 95 |
`GuardedModelAdmin` only requires the standard Django change permission for |
| 96 |
the model itself to access the object permissions management views. Any |
| 97 |
staff user allowed to change a `Post`, for example, can also view and edit |
| 98 |
*every* user's and group's guardian permissions for it, whether or not they |
| 99 |
hold a guardian permission for that. |
| 100 |
|
| 101 |
If you want those views to also require the relevant guardian permission |
| 102 |
(`guardian.view_userobjectpermission`, `guardian.view_groupobjectpermission`, |
| 103 |
`guardian.change_userobjectpermission`, or `guardian.change_groupobjectpermission`, |
| 104 |
depending on the view), use `ReinforcedGuardedModelAdmin` instead: |
| 105 |
|
| 106 |
``` python |
| 107 |
from guardian.admin import ReinforcedGuardedModelAdmin |
| 108 |
|
| 109 |
|
| 110 |
class PostAdmin(ReinforcedGuardedModelAdmin): |
| 111 |
prepopulated_fields = {"slug": ("title",)} |
| 112 |
list_display = ('title', 'slug', 'created_at') |
| 113 |
search_fields = ('title', 'content') |
| 114 |
ordering = ('-created_at',) |
| 115 |
date_hierarchy = 'created_at' |
| 116 |
|
| 117 |
admin.site.register(Post, PostAdmin) |
| 118 |
``` |
| 119 |
|
| 120 |
This is opt-in and not the default, since some applications may rely on the |
| 121 |
existing behavior of granting access based on the model's change permission |
| 122 |
alone. |
| 123 |
|
| 124 |
## Inline Admin Support |
| 125 |
|
| 126 |
Django admin provides inline functionality that allows editing related objects |
| 127 |
on the same page as a parent object. `django-guardian` supports inline admin |
| 128 |
forms through the `GuardedInlineAdminMixin` class. |
| 129 |
|
| 130 |
### Using GuardedInlineAdminMixin |
| 131 |
|
| 132 |
To use inline admin forms with Guardian permissions, you need to inherit from |
| 133 |
`GuardedInlineAdminMixin` along with Django's inline admin classes. Here's an |
| 134 |
example with a `User` and `UserPhone` relationship: |
| 135 |
|
| 136 |
``` python |
| 137 |
from django.contrib import admin |
| 138 |
from django.db import models |
| 139 |
from django.contrib.auth.models import User |
| 140 |
|
| 141 |
from guardian.admin import GuardedModelAdmin, GuardedInlineAdminMixin |
| 142 |
|
| 143 |
|
| 144 |
# Example models |
| 145 |
class UserPhone(models.Model): |
| 146 |
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='phones') |
| 147 |
phone_number = models.CharField(max_length=20) |
| 148 |
phone_type = models.CharField(max_length=10, choices=[ |
| 149 |
('mobile', 'Mobile'), |
| 150 |
('home', 'Home'), |
| 151 |
('work', 'Work') |
| 152 |
]) |
| 153 |
|
| 154 |
class Meta: |
| 155 |
permissions = [ |
| 156 |
('view_userphone', 'Can view user phone'), |
| 157 |
('add_userphone', 'Can add user phone'), |
| 158 |
('change_userphone', 'Can change user phone'), |
| 159 |
('delete_userphone', 'Can delete user phone'), |
| 160 |
] |
| 161 |
|
| 162 |
|
| 163 |
# Inline admin class |
| 164 |
class UserPhoneInline(GuardedInlineAdminMixin, admin.StackedInline): |
| 165 |
model = UserPhone |
| 166 |
extra = 1 |
| 167 |
|
| 168 |
|
| 169 |
# Main admin class |
| 170 |
class UserAdmin(GuardedModelAdmin): |
| 171 |
inlines = [UserPhoneInline] |
| 172 |
list_display = ('username', 'first_name', 'last_name', 'email') |
| 173 |
|
| 174 |
admin.site.register(User, UserAdmin) |
| 175 |
``` |
| 176 |
|
| 177 |
### How It Works |
| 178 |
|
| 179 |
The `GuardedInlineAdminMixin` provides the necessary permission checking methods |
| 180 |
that Django's inline admin forms expect: |
| 181 |
|
| 182 |
- `has_add_permission(request, obj=None)` - Check if user can add inline objects |
| 183 |
- `has_view_permission(request, obj=None)` - Check if user can view inline objects |
| 184 |
- `has_change_permission(request, obj=None)` - Check if user can change inline objects |
| 185 |
- `has_delete_permission(request, obj=None)` - Check if user can delete inline objects |
| 186 |
|
| 187 |
These methods integrate with Guardian's object-level permissions system. When `obj` |
| 188 |
is provided, they check for object-level permissions. When `obj` is `None`, they |
| 189 |
check for global permissions. |
| 190 |
|
| 191 |
### Supported Inline Types |
| 192 |
|
| 193 |
The mixin works with both types of Django admin inline classes: |
| 194 |
|
| 195 |
``` python |
| 196 |
# StackedInline example |
| 197 |
class UserPhoneInline(GuardedInlineAdminMixin, admin.StackedInline): |
| 198 |
model = UserPhone |
| 199 |
extra = 1 |
| 200 |
|
| 201 |
# TabularInline example |
| 202 |
class UserPhoneTabularInline(GuardedInlineAdminMixin, admin.TabularInline): |
| 203 |
model = UserPhone |
| 204 |
extra = 0 |
| 205 |
``` |
| 206 |
|
| 207 |
### Permission Behavior |
| 208 |
|
| 209 |
- **Superusers**: Have all permissions automatically granted |
| 210 |
- **Global permissions**: When no specific object is provided, checks global model permissions |
| 211 |
- **Object-level permissions**: When a parent object is provided, checks permissions on that specific object |
| 212 |
- **Permission isolation**: Users only see inline forms for objects they have appropriate permissions for |
| 213 |
|
| 214 |
!!! tip |
| 215 |
The inline permission checks are performed in the context of the parent object. |
| 216 |
This means users need permissions on the inline model type, and the permission |
| 217 |
checks can be scoped to the specific parent object being edited. |
| 218 |
|
| 219 |
!!! warning |
| 220 |
Make sure to define appropriate permissions in your inline model's `Meta.permissions` |
| 221 |
if you want to use custom permissions beyond Django's default add, change, delete, and view. |