【问题标题】:How to pass a value to a urlpattern using django templating?如何使用 django 模板将值传递给 urlpattern?
【发布时间】:2020-07-12 09:52:13
【问题描述】:

所以我有这个urlpattern,我们可以在地址栏上输入一个数字,它会呈现一个html template,它将在页面上显示输入的数字,我决定通过管道给它更多的功能add:1 到链接href 这样每次我们单击链接时,它都会累加到前一个数字,然后通过在页面上显示该数字来生成响应,但是我无法使用 django 模板让它工作我不断收到页面未找到 404 错误,有人可以帮我解决这个问题吗?这是接受整数的 url 模式

urlpatterns = [
        path('home/<int:num>',views.index,name='index')
        ]

这是 HTML 模板

<!DOCTYPE html>
<html>
    <head>
        <title>Dynamic urls</title>
    </head>
    <body>
        <h1>Page no. {{num}}</h1>
        <a href="{url 'home/{{num|add:1}}' }">Change the page</a>
    </body>
</html>

【问题讨论】:

    标签: django url django-templates url-routing


    【解决方案1】:

    正确的方法是在将新的计算变量作为第二个参数传递给 url 之前,将 with statment 与 add 过滤器结合起来。

    {% with num_=num|add:1 %}
      <a href="{% url 'home' num=num_ %}">Change the page</a>
    {% endwith %}
    

    PS

    • = 周围不应有空格
    • 变量不应以_ 开头
    • 通常的数学运算 (+) 是不允许的,只允许像 add 这样的过滤器

    【讨论】:

    • 这是给我TemplateSyntaxError Could not parse the remainder: '+1' from 'num+1'
    • 我会更新我的答案,也许我们需要在 url 中分配之前将 num 设置为 num + 1。
    • 我更新了我的答案,让我知道这是否适合你
    • @cizrio 不,现在它说“with expects at least one variable assignment”,这就是我的views.py的样子def index(request,num): return render(request,"paths/index.html",{'num':num})
    • @ansme 我更新了我的答案,我测试了它并且它有效。 PS = 周围不应有空格,变量不应以 _ 开头,也不允许仅 filters 使用通常的数学运算,希望这能解决您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2018-08-24
    • 2016-06-16
    相关资源
    最近更新 更多