【问题标题】:django 1.7 how to pass arguments to function regular expressionsdjango 1.7 如何将参数传递给函数正则表达式
【发布时间】:2014-10-09 22:24:28
【问题描述】:

我正在尝试将表的 ID 传递给我的函数,但我不确定发生了什么。 如果我对 ID 号进行硬编码,如果我将 (?Pd+) 与 d+ 一起使用,则它使用尽可能多的数字,就像在教程中一样。不起作用。这应该不同吗?

谢谢大家。

我的网址

from django.conf.urls import patterns, include, url

from polls import views

urlpatterns = patterns('',

    #url(r'^main_site/$', views.main_site),
    url(r'^vote/$', views.vote),
    url(r'^stadistics/$', views.stadistics),


    # using it like this doesn't work
    url(r'^vote/Restaurant_Info/(?P<rest_id>d+)/$', views.restaurant_menu),

    #testing the info of the restaurant
    # hard coding the id of the restaurant does work
    url(r'^vote/Restaurant_Info/4/$', views.restaurant_menu),

我的看法

    def restaurant_menu(request, rest_id="0"):
        response = HttpResponse()
        try:
            p = Restaurant.objects.get(id=rest_id)
            response.write("<html><body>")
            response.write("<p>name of the restaurant</p>")
            response.write(p.name)
            response.write("</body></html>")

        except Restaurant.DoesNotExist:
            response.write("restaurant not found")
        return response

【问题讨论】:

    标签: regex django views


    【解决方案1】:

    您的表达式中缺少反斜杠,目前d+ 匹配字符d 字面意思是“一次或多次”。反斜杠与文字字符组合创建具有特殊含义的正则表达式标记。

    因此,\d+ 将匹配数字 09 “一次或多次”。

    url(r'^vote/Restaurant_Info/(?P<rest_id>\d+)/$', views.restaurant_menu)
    

    【讨论】:

    • 感谢您的解释,我认为是 django,但我应该研究 RE,它对字符串的工作方式是否相同?比如 url(r'^/vote/thanks/(?P\w+)/$', views.thanks),
    • 是的。这是一个很好的参考http://www.regular-expressions.info/
    【解决方案2】:

    你少了一个斜线。应该是(?P&lt;rest_id&gt;\d+)

    【讨论】:

      【解决方案3】:
      url(r"^vote/Restaurant_Info/(?P<rest_id>\d+)/$", views.restaurant_menu),
      

      【讨论】:

        猜你喜欢
        • 2014-01-10
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 2010-11-14
        相关资源
        最近更新 更多