How to Work Model Level Permissions in Django?

Published On: 02/11/2022 | Category: Django


Hi Dev,

If you need to see example of how to work model-level permissions in django. This article will give you simple example of django model-level permissions example. I explained simply step by step how to use permission in django. if you want to see example of model permissions in django then you are a right place. You just need to some step to done model-level permissions in django example.

Describe the operation of Django's groups and permissions. Utilize Django's built-in model permission system to its full potential.

Here i explained simply step by step example of django model permissions example.

Model-level Permissions

You can also add custom permissions to a Django model via the model Meta options.

Let's add an is_published flag to the Post model:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=400)
    body = models.TextField()
    is_published = models.Boolean(default=False)

Next, we'll set a custom permission called set_published_status:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=400)
    body = models.TextField()
    is_published = models.Boolean(default=False)

    class Meta:
        permissions = [
            (
                "set_published_status",
                "Can set the status of the post to either publish or not"
            )
        ]

The UserPassesTestMixin mixin provided by Django can be used in our view to explicitly verify whether a user has the necessary permission or not in order to enforce this permission.

Here's what a class-based view might look like that checks whether a user has permission to set the published status of a post:

from django.contrib.auth.mixins import UserPassesTestMixin
from django.shortcuts import render
from django.views.generic import View

from blog.models import Post

class PostListView(UserPassesTestMixin, View):
    template_name = "post_details.html"

    def test_func(self):
        return self.request.user.has_perm("blog.set_published_status")

    def post(self, request, *args, **kwargs):
        post_id = request.POST.get('post_id')
        published_status = request.POST.get('published_status')

        if post_id:
            post = Post.objects.get(pk=post_id)
            post.is_published = bool(published_status)
            post.save()

        return render(request, self.template_name)

So, with UserPassesTestMixin, you need to override the test_func method of the class and add your own test. Do note that the return value of this method must always be a boolean.

I hope it will help you....

Happy Coding!