url中的django用户名,而不是id [英] django username in url, instead of id
问题描述
在迷你虚拟社区,我有一个profile_view功能,以便我可以查看任何注册用户的配置文件。配置文件视图功能具有作为配置文件所属用户的ID的参数,因此,当我想要访问用户2的配置文件时,例如,我称之为:
http://127.0.0.1:8000/accounts/profile_view/2/
in a mini virtual community, i have a profile_view function, so that i can view the profile of any registered user. The profile view function has as a parameter the id of the user wich the profile belongs to, so that when i want to access the profile of user 2 for example, i call it like that: http://127.0.0.1:8000/accounts/profile_view/2/
我的问题是我想在url中使用用户名,而不是id。
我尝试修改我的代码如下,但它不工作。这是我的代码:
My problem is that i would like to have the username in the url, and NOT the id. I try to modify my code as follows, but it doesn't work still. Here is my code:
查看:
def profile_view(request, user):
u = User.objects.get(pk=user)
up = UserProfile.objects.get(created_by = u)
cv = UserProfile.objects.filter(created_by = User.objects.get(pk=user))
blog = New.objects.filter(created_by = u)
replies = Reply.objects.filter(reply_to = blog)
vote = Vote.objects.filter(voted=blog)
following = Relations.objects.filter(initiated_by = u)
follower = Relations.objects.filter(follow = u)
return render_to_response('profile/publicProfile.html', {
'vote': vote,
'u':u,
'up':up,
'cv': cv,
'ing': following.order_by('-date_initiated'),
'er': follower.order_by('-date_follow'),
'list':blog.order_by('-date'),
'replies':replies
},
context_instance=RequestContext(request))
和我的url:
urlpatterns = patterns('',
url(r'^profile_view/(?P<user>\d+)/$',
profile_view,
name='profile_view'),
提前感谢
推荐答案
你不会显示你尝试过的东西,或者你遇到麻烦。毕竟,这是相当简单的 - 只需将用户名字符串传递给函数而不是一个整数,并根据这一点查找。
You don't show what you have tried, or where you are having trouble. This is fairly simple, after all - just pass a username string to the function instead of an integer, and look up based on that.
def profile_view(request, username):
u = User.objects.get(username=username)
并修改您的网址以允许字符串而不是整数:
and modify your url to allow strings rather than integers:
url(r'^profile_view/(?P<username>\w+)/$',
profile_view,
name='profile_view'),
这篇关于url中的django用户名,而不是id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!