我如何限制在 Django 中的访问?

How do I restrict access in django?

我有一个应用程序,所有用户在注册后都可以发表文章,我怎样才能做到只有有权限的人才能发表文章(比如普通用户和版主/编辑,以及如何授予这些权利。下面是附加代码:

模型。py/blogapp

 class Post(models.Model):
        title = models.CharField(verbose_name=("Заголовок"), max_length=200)
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        header_image = models.ImageField(verbose_name=("Заглавное Изображение"), null=True, blank=True, upload_to="images/" )
        body = RichTextField(verbose_name=("Тело Статьи"), blank=True, null=True)
        #body = models.TextField(blank=True, null=True)
        post_date = models.DateTimeField(auto_now_add=True)
        category = models.CharField(verbose_name=("Категория"), max_length=200)
        snippet = models.CharField(verbose_name=("Фрагмент Статьи"), max_length=200)
        likes = models.ManyToManyField(User, related_name='blog_post')
        updated_on = models.DateTimeField(auto_now= True)
        
    
        def total_likes(self):
            return self.likes.count()
    
    
        def __str__(self):
            return self.title + ' | ' + str(self.author)
    
        def get_absolute_url(self):
            return reverse('article_detail', args=[str(self.id)])

观看次数。py/members

class CreateProfilePageView(CreateView):
    model = Profile
    form_class = ProfilePageForm
    template_name = "registration/create_user_profile.html"
    #fields = '__all__'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

class EditProfilePageView(generic.UpdateView):
    model = Profile
    template_name = 'registration/edit_profile_page.html'
    fields = ['bio', 'profile_pic', 'website_url', 'instagram_url', 'twitter_url', 'status',  'age']

    success_url = reverse_lazy('home')

class ShowProfilePageView(DetailView):
    model = Profile
    template_name = 'registration/user_profile.html'

    def get_context_data(self, *args, **kwargs):
        #users = Profile.objects.all()
        context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs)

        page_user = get_object_or_404(Profile, id=self.kwargs['pk'])

        context["page_user"] = page_user
        return context

class PasswordsChangeView(PasswordChangeView):
    form_class = PasswordChangingForm
    #form_class = PasswordChangeForm
    success_url = reverse_lazy('password_success')
    #success_url = reverse_lazy('home')

def password_success(request):
    return render(request, 'registration/password_success.html', {})

class UserRegisterView(generic.CreateView):
    form_class = SignUpForm
    template_name = 'registration/registr.html'
    success_url = reverse_lazy('login')


class UserEditView(generic.UpdateView):
    form_class = EditProfileForm
    template_name = 'registration/edit_profile.html'
    success_url = reverse_lazy('home')

    def get_object(self):
        return self.request.user

观看次数。py/blogapp

class HomeView(ListView):
    model = Post
    queryset = Post.objects.filter(draft=False)
    cats = Category.objects.all()
    template_name = 'home.html'
    ordering = ['-post_date']
    paginate_by = 6

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(HomeView, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

def CategoryListView(request):
    cat_menu = Category.objects.all()
    return render(request, 'category_list.html', {'cat_menu':cat_menu})


def CategoryView(request, cats):
    category_posts = Post.objects.filter(category = cats). order_by('-post_date')
    return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})


class ArticleDetailView(HitCountDetailView):
    model = Post
    template_name = 'post_detail.html'
    count_hit = True


    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)

        stuff = get_object_or_404(Post, id=self.kwargs['pk'])
        total_likes = stuff.total_likes()

        context["cat_menu"] = cat_menu
        context["total_likes"] = total_likes
        return context



class AddPostView(CreateView):
    model = Post
    form_class = PostForm
    template_name= 'add_post.html'
    #fields = '__all__'

class AddCommentView(CreateView):
    model = Comment
    form_class = CommentForm
    template_name= 'add_comment.html'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)

    def get_success_url(self):
        return reverse_lazy('article_detail', kwargs={'pk': self.kwargs['pk']})

class AddCategoryView(CreateView):
    model = Category
    template_name= 'add_category.html'
    fields = '__all__'


class UpdatePostView(UpdateView):
    model = Post
    template_name = 'update_post.html'
    form_class = EditForm
    #fields = ['title', 'body']

class DeletePostView(DeleteView):
    model = Post
    template_name = 'delete_post.html'
    success_url = reverse_lazy('home')

如果您需要更多代码,我会附上,谢谢,请原谅我的英语)

你好asd你可以像这样在你的配置文件模型中添加这样的标志

class Profile(models.Model):
    user = models.ForeignKey(User,on_delete=models.PROTECT)
    is_moderator = models.BooleanField(default=False)
    is_editor = models.BooleanField(default=False)#you can add many more as you want

您可以在模板或视图中像这样验证用户 在 views.py

def check_user(request):
    moderator_profile = Profile(user_id=request.user.id,is_moderator=True)
    editor_profile = Profile(user_id=request.user.id,is_editor=True)
    if user_profile:
        return redirect('url_for_moderator')
    elif editor_profile:
        return redirect('url_for_editor')

您可以将数据传递给模板并为特定用户提供特定功能 像这样

在你的 views.py

def get_post(request):
    user_profile = Profile.objects.filter(user=request.user.id)
    return render(request,"post.html",{"user_profile":user_profile})

和里面post.html

{% if user_profile.is_editor or user_profile.is_moderator %}
<button>Edit</button>
{% endif %}

如果您不喜欢这种方式,您可以用更好的方式进行检查 post https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html