【问题标题】:Django URLS, using a ? in the URLDjango URL,使用 ?在网址中
【发布时间】:2012-08-18 06:02:15
【问题描述】:

我正在尝试做一些 Django URL 匹配。

我想要一些我有http://mysite.com/base?sort=type1/http://mysite.com/base?sort=type2/ 等的网址。

我不知道如何匹配这些表达式的 URL:我对 Django 很陌生,以前从未使用过 Reg Ex。

我的“基础”应用程序中的 urls.py 是:

url(r'^$','base.views.main, name='main'),

我不知道该放什么来匹配我的网址和问号。

我正在尝试类似的东西

url(r'^?sort=popular/$', 'base.views.main_popular', name='main_popular'),

感谢您的帮助!

【问题讨论】:

    标签: regex django urlconf


    【解决方案1】:

    您没有将这些与正则表达式匹配。 ? 之后的元素不是 URL 的一部分,它们是查询参数,可以通过 request.GET 从您的视图中访问。

    【讨论】:

      【解决方案2】:

      ?不会匹配“?”在 url 中,它有自己的含义,您可以在此处查找:
      Python Regular Expressions 如果要匹配“?”的确切字符在您的 url 中,您必须以某种方式对其进行转义(因为它在 RegExs 中具有含义)所以您可能想通过“\”(反斜杠)转义它 所以你会写 \?sort ....

      编辑:
      好的,您在 cmets 中所说的内容似乎是您的问题,当您使用 GETGET 方法字典参数呈现 /main/ 的模板时,main?sort=popular 出现在您的 url 模式上,只需写一个区分 GETPOST 的函数,在 GET 部分中,有类似 sort_by = request.GET.get('sort','') 的东西,然后使用 sort_by 变量的值进行相应的排序,就像:

      def main_handler(request):
           if request.method == "POST":
                 whatever ... 
           if request.method == "GET" :
                 sort_by = request.GET.get('sort','')
                 if sort_by:
                       sort by what sort points to 
                       return "the sorted template"
           return render_to_response(the page and it's args)
      

      然后放手?在 url 模式中,当您使用 GET 参数请求页面时添加。

      【讨论】:

      • 我试过这样做,不幸的是它并没有真正成功——我不太清楚为什么。
      • 您可能也想发布该代码?但实际上,在这样的 url (sort=popular) 开头有一个问号似乎很奇怪
      • 基本上我有一个网页,其内容可以根据排序进行排序。 main?sort=popular 表示您仍在主页上,而 main/popular/ 表示您仍在主页上。我正在使用 url(r'^\?sort=popular/$', 'base.views.main_popular', name='main_popular')
      【解决方案3】:

      您不需要这样做。相反,您可以制作一个通用模板和视图。

      #And this is the views.py
      def main_handler(request):
          if request.method == "GET":
              sort_parameter = request.GET.get('sort')
              if sort_parameter:
                   #the code to sort the database objects on basis of the sort parameter
                   return render(The template and its kwargs)
              #your other code
      

      您的网址文件应如下所示:

      urlpatterns = [
      url(r'base/', 'base.views.thecommonview', name='main'),
      ]
      
      

      【讨论】:

        猜你喜欢
        • 2011-06-03
        • 2020-01-22
        • 2015-10-06
        • 2016-04-16
        • 1970-01-01
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 2019-04-08
        相关资源
        最近更新 更多