2015-01-15 27 views
1

假设我要传递的用户名中的网址:如何在Django通过特殊字符的URL

username = '[email protected]' 

所以在网址,它是这样的:

url(r'(?P<user_name>\w+)/$', 'user_related.views.profile', name='profile'), 

而获取该用户在views.py:

def profile(request, user_name): 
    user = User.objects.get(username=user_name) 

    return render(request, 'user_profile.html', {'user':user}) 

但我得到一个错误:

User matching query does not exist. 

因为django自动将@转换为%40。我怎样才能将实际的username传递给视图?请帮我解决这个问题。谢谢!从标准urllib模块

回答

4

使用unquote功能:

from urllib import unquote 

user = User.objects.get(username=unquote(user_name)) 

顺便说一句,据我了解的正则表达式在您的网址()应该是[\[email protected]%.]+。普通\w+不匹配[email protected]kakar%40gmail.com

+0

完美!我仍然收到错误“用户匹配查询不存在”,但您的编辑帮助我!谢谢!然而,只是想知道,在urls中使用'%'是什么,因为它只会使用'@'? – Kakar

+0

'@'在URL(http:// user:[email protected])中有特殊含义,因此在“URI”RFC中建议将'@'编码为'%40'。但AFAIK在现实生活中可以安全地在URL路径中使用'@'。 – catavaran

+0

这个答案是拯救生命的!非常感谢。 –