【问题标题】:Django - 2 URLS with same regex, but different variables and viewsDjango - 2 个具有相同正则表达式但变量和视图不同的 URL
【发布时间】:2017-08-02 04:12:19
【问题描述】:

我有以下网址:

url(r'^(?P<college_name>\w+)/$', views.detail, name="detail"),
url(r'^(?P<photographer_username>\w+)/$', views.photographer, name="photographer"),

当我输入/college_name url 时它可以工作,但是当输入像website.com/johnsmith 这样的摄影师时,它只会搜索第一个 url 模式然后停止。

如果我把photographer url 模式放在第一位,它适用于摄影师而不是大学。

如何修复它以使其适用于两者?

【问题讨论】:

  • 您希望计算机如何确定您要访问的 URL?这是做不到的。

标签: python django python-2.7 url django-urls


【解决方案1】:

您应该区分这两种 url 模式,否则后者将永远被前者所掩盖。

也许在两者前面加上一个唯一的字符串:

url(r'^college/(?P<college_name>\w+)/$', views.detail, name="detail"),
url(r'^photographer/(?P<photographer_username>\w+)/$', views.photographer, name="photographer"),

【讨论】:

    【解决方案2】:

    这怎么可能奏效?正如您所说,正则表达式是相同的。那么 Django 怎么知道你指的是哪个视图呢?它不能,所以它只选择第一个。

    解决此问题的唯一方法是更改​​您的网址,使它们不仅具有名称:例如“/photographer/(?P\w+)/$”等。

    【讨论】:

      【解决方案3】:

      正如其他人所说,计算机无法自行决定选择哪个视图。最好的解决方案是使用不同的路径,例如 /photographer//college/

      如果你坚持两个视图使用相同的 url scheme,你需要告诉程序如何区分。

      网址定义:

      url(r'^(?P<photographer_or_college>\w+)/$', photographer_or_college_view, name="photographer_or_college")
      

      选择其中一个的视图:

      def photographer_or_college_view(request, photographer_or_college):
          try:
              photographer = Photographer.objects.get(photographer_name=photographer_or_college)
          except Photographer.DoesNotExist:
              pass
          else:
              return photographer_view(request, photographer)
      
          college = get_object_or_404(College, college_name=photographer_or_college)
          return college_view(request, college)
      

      不建议这样做,因为如果存在名称冲突,您会遇到问题。

      【讨论】:

        猜你喜欢
        • 2011-01-22
        • 1970-01-01
        • 2015-05-12
        • 1970-01-01
        • 2017-06-25
        • 2022-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多