我想为每个创建的帐户创建一个个人资料页面。创建后,可以像这样访问用户配置文件
http://example.com/用户名 http://example.com/username
但在创建之前,我应该验证该 url 是否已经可用并且未被现有 url 模式采用。例如:会有一个类似的页面
http://example.com/about http://example.com/about
现在“about”不是有效用户。但这是一个有效的 url 模式。我应该能够阻止创建名为“about”的用户。为此,除了检查具有该名称的用户是否已存在之外,我还需要检查 url 模式。这个怎么做?
一个简单的方法是为个人资料页面设置如下 url 模式:http://example.com/user/用户名 http://example.com/user/username
但我强烈要求拥有如下所示的个人资料页面http://example.com/用户名 http://example.com/username
您可以简单地尝试将地址解析为视图:
from django.core.urlresolvers import resolve
from myapp.views import user_profile_view
try:
my_view = resolve("/%s/" % user_name)
if my_view == user_profile_view:
# We match the user_profile_view, so that's OK.
else:
# oops, we have another view that is mapped on that URL
# you already have something mapped on this address
except:
# app doesn't have such path
EDIT:
您还可以通过不同的方式进行检查:
def user_profile_view(request, user_name):
# some code here
user_profile_view.name = "User Profile View"
然后上面的检查可能是:
if getattr(my_view, "name", None) == "User Profile View":
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)