python - 如何在 Django 中搜索带有 url 模式的字符串?

标签 python django

我想为每个创建的帐户创建一个个人资料页面。创建用户个人资料后,可以像这样访问

http://example.com/username

但在创建之前,我应该验证该 url 是否已经可用并且没有被现有的 url 模式占用。例如:会有一个像

这样的页面

http://example.com/about

现在“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/

相关文章:

python - 无法在 Python 3 上安装 wsgiref

django - 基于类的 View 有什么优势?

Django 1.10.1 'my_templatetag' 不是注册标签库。必须是 : 之一

html - 将 css 集成到 Django 模板中

python - Django 博客中的图像失败

python - 如何获取输入 gtk.entry 字段的值并在按钮信号之外使用它

python - 在 python 库中导入和裁剪 jpeg 的快速方法

Python:为什么使用 re.IGNORECASE 编译的正则表达式会删除第一个字符?

Python - 访问类方法(使用twisted)

python - Django - 只有在 HttpResponseRedirect 之后才能访问页面