创建禁区

时间:2019-05-08 14:04:07

标签: python-3.x django-views django-2.2

我正在尝试为网站建立一个禁区,只有注册的用户才能看到他的个人资料和帖子。员工用户可以查看所有用户的个人资料和相关帖子。

这是 models.py

...
from django.contrib.auth.models import User

class Post(models.Model):
    authorized_users = models.ManyToManyField(
        User,
        related_name="user_set",
        default=1,
        )
    title = models.CharField(max_length=100)
...

如您所见,一篇文章可以拥有多位作者( authorized_users )。

这是 views.py

from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User


@permission_required('user.is_staff', raise_exception=True)
def listUsers(request):
    users_list = User.objects.all()
    context = {"users_list": users_list}
    template = 'usermanager/users_list.html'
    return render(request, template, context)

@permission_required('post.authorized_users=username', raise_exception=True)
def singleUser(request, username):
    user_single = get_object_or_404(User, username=username)
    context = {"user_single": user_single}
    template = 'usermanager/single_user.html'
    return render(request, template, context)

def listPost(request):
    posts_list = Post.objects.all()
    context = {"posts_list": posts_list}
    template = 'usermanager/list_post.html'
    return render(request, template, context)

def singlePost(request, pk):
    post_single = get_object_or_404(Post, pk=pk)
    context = {"post_single": post_single}
    template = 'usermanager/single_post.html'
    return render(request, template, context)

如果我以工作人员身份登录,则可以看到用户列表( view listUsers )和具有所有帖子的单个用户( view singleUser );但是如果我以非职员用户身份登录,则会看到消息 403 Forbidden 。这不是我想要看到的内容,因为我只想查看我的个人资料和帖子。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题:

def userProfile(request, username):
    if request.user.username == username:
        user_details = get_object_or_404(UserProfile, username=username)
    elif request.user.is_staff:
        user_details = get_object_or_404(UserProfile, username=username)
    else:
        raise PermissionDenied
    context = {
        "user_details": user_details,
        }
    template = 'usermanager/reading/user_profile.html'
    return render(request, template, context)

对于其他视图也可以使用相同的策略。