【问题标题】:URL pattern in django to match limited set of wordsdjango 中的 URL 模式以匹配有限的单词集
【发布时间】:2020-12-21 07:42:35
【问题描述】:

我在 Django 中有一个 URL 模式,其中有一个变量(称为 name),它应该只采用选择的单词列表之一。像这样的:

path("profile/<marta|jose|felipe|manuela:name>/", views.profile),

所以基本上只有这些路径是有效的:

  • 个人资料/玛塔/
  • 个人资料/何塞/
  • 个人资料/felipe/
  • 个人资料/manuela/

我该如何在 Django url 模式中进行配置?上面的语法试图说明这个想法,但不起作用。我见过this ten year old question,但它在 url 模式文件中使用了以前的格式,所以我想现在应该以不同的方式完成......?

【问题讨论】:

标签: python django url-pattern


【解决方案1】:

为什么不把它们放在眼里?

from django.http import Http404

def profiles(request, name):
    if not name in ['marta', 'jose', 'felipe', 'manuela']:
        raise Http404('You shall not pass!')

或者你可以简单地使用re_path

urlpatterns = [
    re_path(r'^profile/(?P<name>marta|jose|felipe|manuela)/$', views.index, name='index'),
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-02
    • 2011-11-03
    • 2012-06-18
    • 2021-08-24
    • 2013-12-10
    • 1970-01-01
    • 2014-12-13
    • 2014-10-01
    相关资源
    最近更新 更多