Django, a high-level Python web framework, utilizes a permissions and authorization system that allows developers to restrict access to certain parts of their site to certain groups of users. For management of object-level and model-level permissions, Django uses the Django Content Type System. Here is a step-by-step process on how to do so.
1. Simple Model Permissions in Django
Django automatically provides add, change, delete, and view permissions for every Django model that has been used in a project (“Django Documentation,” 2021). After being authenticated, a user would use these permissions. For instance, in an eCommerce site built with Django, you may have models such as Product, Order, ProductImage. If a user has the add permission for Product models, they can add new products to the database.
```
user.has_perm(‘app_name.add_modelname’)
user.has_perm(‘app_name.view_modelname’)
user.has_perm(‘app_name.change_modelname’)
user.has_perm(‘app_name.delete_modelname’)
```
Django’s authentication framework uses these permissions as a way of determining what a user can do.
1. Object Level (Row Level) Permissions
Row Level Permissions are more complicated and are not automatically included in Django. To implement this, e.g., allowing a certain user to only modify a Product that they created, you’d need to install third-party libraries like `django-guardian`. After installation, you can use it by assigning the function to a user:
```
from guardian.shortcuts import assign_perm
assign_perm(‘change_product’, user, productinstance)
```
Then, you can check the permission with: `user.has_perm(‘change_product’, productinstance)`.
1. Custom Permissions
Django allows you to add your custom permissions to models. You can add a list of permissions in your Meta class in models.py:
```
class YourModel(models.Model):
…
class Meta:
permissions = ((“custom_permission”, “Can perform custom permission.”),)
```
Later, you can check if the user has the custom permission through user.has_perm(‘app_name.custom\_permission’).
1. PermissionRequiredMixin
Django also provides views to handle permissions; one of them is `PermissionRequiredMixin`. If a view is using this mixin, all users who want to access the view should have all the permissions mentioned in the `permission_required` option.
```
from django.contrib.auth.mixins import PermissionRequiredMixin
class YourView(PermissionRequiredMixin, views.View):
permission_required = (‘app_name.custom_permission’,)
```
Remember to handle what happens if the user doesn’t have the permission by setting the `raise_exception` option.
Sources:
“Django Documentation: Django Authentication” (2021) docs.djangoproject.com
“Django Guardian” (2021) django-guardian.readthedocs.io
“Django Documentation: Working with Mixins” (2021) docs.djangoproject.com