2๐
โ
Do you really need the user parameter in the profile URL? If you only want it work for the current user, then why not simply drop the user
parameter:
# urls.py
url(r'^accounts/profile/$',
UserProfileView.as_view(),
name='user_profile_view'
),
# views
class UserProfileView(View):
@method_decorator(login_required)
def get(self, request):
profile = get_object_or_404(UserProfile, user=request.user)
return render(request, 'accounts/profile.html', {'profile': profile})
In the code you posted, the UserProfileView.get
method was not using the user
parameter anyway.
UPDATE
If you want to keep the user
parameter and make it work the way you want, you can change the view like this:
from django.http import Http404
class UserProfileView(View):
@method_decorator(login_required)
def get(self, request, user):
if request.user.username == user:
profile = get_object_or_404(UserProfile, user=request.user)
return render(request, 'accounts/profile.html', {'profile': profile})
else:
raise Http404
Btw, since user
in the parameter list of the get
method is really just the username as opposed to a user object, it would be better to rename it to username
, to avoid confusion.
๐คjanos
Source:stackexchange.com