【问题标题】:Django: Named Url's/ Same regex, different NamesDjango:命名网址的/相同的正则表达式,不同的名称
【发布时间】:2014-12-18 05:27:02
【问题描述】:

我有一个urls.py 文件,其中包含多个具有相同命名参数和正则表达式但名称不同的网址。当我使用 {% url 'name' param %} 从模板调用视图函数时,它会调用 urls.py 文件中第一个出现的函数,而不管名称。这里是urls.py的内容:

urlpatterns = patterns('accountsearch.views',
url(r'^$', 'account_search', name='account_search'),
url(r'(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$','reset_password',name='reset_password'),
url(r'(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$','reset_securityquestions',name='reset_securityquestions'),

我正在尝试使用以下模板从模板中调用reset_securityquestions:

"{% url 'reset_securityquestions'   account.uuid user.uuid %}">

但它改为调用reset_password。

如果我将urls.py 中的网址顺序更改为:

urlpatterns = patterns('accountsearch.views',
url(r'^$', 'account_search', name='account_search'),
url(r'(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$', 'reset_securityquestions',
    name='reset_securityquestions'),
url(r'(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$', 'reset_password', name='reset_password'),

并使用以下方式致电reset_password:

{% url 'reset_password' account.uuid user.uuid %}

它调用reset_security_questions 函数。我哪里错了?

【问题讨论】:

    标签: python regex django


    【解决方案1】:

    Django 总是先匹配 url 模式,所以将 url 重写为:

    urlpatterns = patterns('accountsearch.views',
       url(r'^$', 'account_search', name='account_search'),
       url(r'^reset-password/(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$','reset_password',name='reset_password'),
       url(r'^security-question/(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$','reset_securityquestions',name='reset_securityquestions'),
    

    【讨论】:

      【解决方案2】:

      如果它们都具有完全相同的 url 模式,我不明白您如何期望 Django 知道要使用哪个 URL。当请求进来时,Django 所要做的就是 URL 本身,它总是会尝试按顺序匹配它们。使用切换模式后,您会发现 reset_password 视图现在不起作用。

      你需要给 Django 一些区分它们的方法。通常会使用一些文字文本,作为前缀或后缀,例如:

      r'reset/(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$'
      r'security/(?P<account_uuid>[a-zA-Z0-9\-]+)/(?P<user_uuid>[a-zA-Z0-9\-]+)/$'
      

      【讨论】:

      • 我是 Django 新手,我在想,因为我指定了 url 的名称,所以它可以使用它来调用视图。我想我错了,现在它工作正常。谢谢。
      猜你喜欢
      • 2011-01-22
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2020-01-12
      • 2010-10-25
      • 2010-09-21
      相关资源
      最近更新 更多