Domanda

I have a Django project that uses profiles for user information. Things are somewhat working except for one aspect... Here are code snippets to describe my problem.

In the template:

<li><a href="/accounts/{{ user.username }}/profile/">Profile</a></li>

In views.py

class UserProfileView(View):
    @method_decorator(login_required)
    def get(self, request, user):
        profile = get_object_or_404(UserProfile, user=request.user)
        return render(request, 'accounts/profile.html', {'profile': profile})

In urls.py

url(r'^accounts/(?P<user>.+)/profile/$', 
    UserProfileView.as_view(),  
    name='user_profile_view'
),

I've tried variations for the named group, and this is what I found to work. The problem is, I can use any string in between /accounts/ and /profile/ (obviously) and it works. What I want to accomplish is to have only the current user's username be valid in the URL and otherwise throw a 404.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top