Home > Blockchain >  permission_required for user who only users who are part of a group ,in view based class
permission_required for user who only users who are part of a group ,in view based class

Time:07-24

Based on a tutorial,i have a view with a restriction on the display of data, based on a permission of the form "book.can_view" in class BookDetailView

This works, but the probleme are every user not have access to the view I'd like to do the same thing but using the group name. . I would like only users who are part of a group named "premium" to have access to this page

my views.py

from django.shortcuts import render
from django.contrib.auth.mixins import PermissionRequiredMixin

from django.http import HttpResponse

from catalog.models import Book, Author, BookInstance, Genre
from accounts.models import CustomUser

from django.views.generic import ListView, DetailView


class BookListView(ListView):
    model = Book
    paginate_by = 10
    #permission_required = 'catalog.view_book'


def index(request):    

    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    # Available books (status = 'a')
    num_instances_available = BookInstance.objects.filter(
        status__exact='a').count()

    # The 'all()' is implied by default.
    num_authors = Author.objects.count()

    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,

    }

    # Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)


class BookDetailView(PermissionRequiredMixin, DetailView):
    """Generic class-based detail view for a book."""
    model = Book
    template_name = "catalog/permission_required.html"
    permission_required = 'book.can_view'# change this line ?


class AuthorListView(ListView):
    """Generic class-based list view for a list of authors."""
    model = Author
    paginate_by = 10


class AuthorDetailView(DetailView):
    """Generic class-based detail view for an author."""
    model = Author

thank for help

CodePudding user response:

I see it more or less like this.

from django.contrib.auth.mixins import UserPassesTestMixin
from django.contrib.auth.models import Group

class BookDetailView(UserPassesTestMixin, LoginRequiredMixin, DetailView):
    model = Book
    template_name = "catalog/permission_required.html"

    def test_func(self):
        premium_group = Group.objects.filter(name = "premium") # or get
        if self.request.user in premium_group:
            return True
        else:
            return False

CodePudding user response:

Thank you ttt, the code you told me

def test_func(self):
        premium_group = Group.objects.filter(name = "premium") # or get
        if self.request.user in premium_group:
            return True
        else:
            return False

restricts access to all users, and i have page 403 , even the one who has the right to the "premium" group and even the admin, this sends you to the error page. I may have forgotten to mention that I use a custom user, here is the code of the model

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models


class CustomUserManager(BaseUserManager):
    def create_user(self, email, password):
        if not email:
            raise ValueError('Vous devez entrer une adresse email.')
        email = self.normalize_email(email)
        user = self.model(email=email)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password):
        user = self.create_user(email=email, password=password)
        user.is_staff = True
        user.is_admin = True
        user.save()
        return user


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        max_length=255,
        unique=True,
        blank=False
    )
    nom = models.CharField(max_length=50, blank=False, unique=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = "email"

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"

        return True

    def __str__(self):
        return self.email

I tested this other code

def test_func(self):
        ok = Group.objects.all()
        if self.request.user.has_perm('premium'):
            return ok
        return ok.filter(user=self.request.user)

this time it shows me the correct error page, but even users who have group permission are directed to the error page

  • Related