permission_required适用于在基于视图的类中仅属于组的用户



根据教程,我有一个视图,基于窗体"的权限,对数据的显示进行了限制;book.can_view"类内BookDetailView

这是可行的,但问题是每个用户都不能访问视图。我想做同样的事情,但使用组名。我只希望是名为";溢价;访问此页面

我的观点.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

感谢的帮助

我看到它或多或少是这样的。

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

谢谢ttt,你告诉我的代码

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

限制对所有用户的访问,并且我有页面403,即使是对";溢价;组,甚至管理员,这会将您发送到错误页面。

最新更新