1π
β
If i got the question then the most easy way (as per me) is to use decorators.
Use a login decorator to allow a route only when the user is logged in.
from django.contrib.auth.decorators import login_required
# then at the user_detail route i.e, the route which shows the profile of a user.
@login_required(login_url='your_login_route') #'your_login_route' is the route of your login page. So if a user is not logged in, he will be redurected to 'your_login_route'
def user_detail(request, user_id):
...
EDIT: If you only want to show the profile to the same user and not to any other user you can try this;
def user_detail(request, user_id):
if request.user.id == user_id:
"show the profile"
else:
'show an error page'
Please make sure that the user_id
which you are using for recognition is same as the userβs id in database.
π€Irfan wani
0π
You can do like this.
@login_required
def user_detail(request, user_id):
user = request.user
return render (request, 'users/user_detail_2.html',{'user':user})
Or you can use request.user in templates, but you have to check the user is_authenticated.
π€yanqzhi
- [Answered ]-Django admin: filtering by "now" in list view
- [Answered ]-What is the proper way to implementing the revoke(Blacklist) token URL in FastAPI, Django, Flask?
- [Answered ]-Django Model Won't Validate or Not Installed
0π
class MyView(DetailView):
Model = User
def get_object(self):
"""get obj here, either slug or pk"""
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['user'] = self.object.filter(user=request.user)
return context
π€Jonas Moloto
- [Answered ]-Getting error when trying to run to server with Channels
- [Answered ]-Django url dispatching and middleware
- [Answered ]-Getting DUPLICATE error when logging in existing user with Django
- [Answered ]-Is it possible to create related objects on parent creation automatically in Django?
Source:stackexchange.com