In Django, how do I write a url.py where users/self/ is the same as users/<pk>/, where <pk> is your logged in user pk?

老子叫甜甜 提交于 2019-12-11 05:19:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!