I have this model:
class Student(Model):
user = OneToOneField(CustomUser, on_delete=CASCADE, related_name='student', )
and this url:
path('students/<int:student_pk>/', student, name='student')
and this view:
@login_required
def student(request, student_pk):
return HttpResponse('This is your personal panel')
Well, by using login_required decoration I am restricting users that are not logged in to see student panel page. However, other students who are logged in can see other's panels.
How can I restrict them from this?
I can do this:
@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')
However, I prefer to do it in decorator. For example log out the logged in student with primary key pk=1 if he/she entered this in the url: www.example.com/students/2
Try this:
and use that like:
This should do what you want, but keep in mind that it's not generally a good idea, unless you have a very special use-case. Basically, what you should do is to have a url like
/profile/and show the user profile based on therequest.user; This is much more cleaner way.