问题
I'm trying to build a restricted area for a website in which only the registered user can see his personal profile and his posts. The staff users can see all users profile and related posts.
This is 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)
...
As you can see one post can have more then one author(authorized_users).
This is 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)
If I'm logged in as staff I can see the list of users(view listUsers) and the single user with all his posts(view singleUser); but if I'm logged in as non staff user I see the message 403 Forbidden. This isn't what I want to see becouse I want to see only my profile and my posts.
How I can solve this?
回答1:
I've solved is using this:
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)
It is possible to use the same strategy for the others views.
来源:https://stackoverflow.com/questions/56042646/create-a-restricted-area