问题
I am trying to write a url.py
where I have a simple view for users
urlpatterns = patterns( 'doors.view',
url( r'^users/$' , 'users_list' , name = 'users_list' ),
url( r'^users/(?P<pk>\d+)/$', 'users_detail', name = 'users_detail' ),
url( r'^users/self/$' , # do some sort of redirect here ),
)
The problem with the redirect is I don't know the pk
of the logged in user in url.py
. In view.py
, I would obviously do a @login_required
to be able to access users/self/
.
Maybe I am doing this wrong way? What do you guys suggest I do?
回答1:
My suggestion (not sure if it's the easiest one) would be to create a new view, where you can grab the user's pk and then call the users_detail
view:
@login_required
def self_detail(request):
return users_detail(request, request.user.pk)
回答2:
You could also do the following in urls.py:
urlpatterns = patterns( 'doors.view',
url( r'^users/$' , 'users_list' , name = 'users_list' ),
url( r'^users/(?P<pk>\d+)/$', 'users_detail', name = 'users_detail' ),
url( r'^users/self/$' , 'users_detail', {'pk'='self'} ),
)
And then in views.py:
if pk == 'self':
user = request.user
else:
user = User.objects.get(pk=pk)
回答3:
Create a view that invokes user_detail()
with the value from request.user.pk
.
来源:https://stackoverflow.com/questions/9849546/in-django-how-do-i-write-a-url-py-where-users-self-is-the-same-as-users-pk