我想为每个创建的帐户创建一个个人资料页面。创建用户个人资料后,可以像这样访问
但在创建之前,我应该验证该 url 是否已经可用并且没有被现有的 url 模式占用。例如:会有一个像
这样的页面现在“about”不是一个有效的用户。但它是一个有效的 url 模式。我应该能够阻止创建名为“about”的用户。为此,除了检查具有该名称的用户是否已经存在之外,我还需要检查 url 模式。如何做到这一点?
一个简单的方法是为个人资料页面设置如下所示的 url 模式: http://example.com/user/username
但是我强烈要求有如下的个人资料页面 http://example.com/username
最佳答案
您可以简单地尝试将地址解析为 View :
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
编辑:
你也可以用不同的方式进行检查:
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":
...
关于python - 如何在 Django 中搜索带有 url 模式的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11207302/