如何限制未经授权的用户访问django中的不同页面

如何限制未经授权的用户访问django中的不同页面,django,security,decorator,login-required,Django,Security,Decorator,Login Required,我有这个模型: class Student(Model): user = OneToOneField(CustomUser, on_delete=CASCADE, related_name='student', ) 这个网址: path('students/<int:student_pk>/', student, name='student') 嗯,通过使用login_required装饰,我限制未登录的用户查看学生面板页面。但是,其他登录的学生可以看到其他人的面板 我如

我有这个模型:

class Student(Model):
    user = OneToOneField(CustomUser, on_delete=CASCADE, related_name='student', )
这个网址:

path('students/<int:student_pk>/', student, name='student')
嗯,通过使用login_required装饰,我限制未登录的用户查看学生面板页面。但是,其他登录的学生可以看到其他人的面板

我如何限制他们这样做

我可以这样做:

@login_required
def student(request, student_pk):
    student_ins = get_object_or_404(Student, pk=student_pk)
    if student_ins == request.user.student:
        return HttpResponse('This is your personal panel')
    else:
        return HttpResponse('Please do not try to see other students' panels! You are not authorized to do this')
然而,我更喜欢在decorator里做。例如,如果登录的学生在url:www.example.com/students/2中输入了主键pk=1,请注销该学生。请尝试以下操作:

from django.contrib.auth import logout

def check_profile(function):
  @wraps(function)
  def wrap(request, *args, **kwargs):
      user = request.user
      student_ins = get_object_or_404(Student, pk=kwargs.get(student_pk))
      if not student_ins == user:
          logout(request)
          return HttpResponse('Please do not try to see other students' panels! You are not authorized to do this')
  return wrap
然后像这样使用:

@check_profile
@login_required
def student(request, student_pk):
    #...

这应该满足您的需要,但请记住,这通常不是一个好主意,除非您有一个非常特殊的用例。基本上,您应该做的是创建一个类似/profile/的url,并根据请求显示用户配置文件;这是一种更简洁的方式。

我简化了问题。我有不同的用户类型。我有老师和学生。教师可以登录并注册学生。然后我有了这个url:teachers/2/student/1和这个url students/1,这样你就可以保留你的teachers/2/student/url,并将其限制为仅限教师使用,但每个学生的个人资料都有student/profileprofile@AminBa我接受了你的要求;谢谢你。也可以考虑把答案标记为接受或告诉我们这有什么不对。
@check_profile
@login_required
def student(request, student_pk):
    #...