【问题标题】:Passing variable through Django template url tag通过 Django 模板 url 标签传递变量
【发布时间】:2019-07-31 16:06:17
【问题描述】:

我试图通过 Django 模板 url 标签传递一个变量,但收效甚微。

我在 urls.py 中的路径:

path("viewListing/<int:listingID>", views.bookListing, name="viewListing")

在模板中,我使用 javascript 生成带有 for 循环的 listingID。

for(j=0; j<5; j++){
  var thisID = (data[j].id)
  imgA.href = "{% url 'viewListing' thisID %}";
}

但是,我收到了这个错误

Reverse for 'viewListing' with arguments '('',)' not found. 1 pattern(s) tried: ['viewListing/(?P<listingID>[0-9]+)$']

如果我传递一个数字而不是 thisID,例如 1,则代码可以正常工作。

所以我的问题是,我怎样才能使这个与变量一起工作。

【问题讨论】:

    标签: django django-templates django-urls


    【解决方案1】:

    您不能在 Javascript 中使用 django 标签。他们是服务器端。您可以做的是将 url 缓存在一个变量中,然后将 ID 连接到它,如下所示:

    for(j=0; j<5; j++){
        var thisID = (data[j].id)
        var listing_url = "{% url 'viewListing' listingID=9999 %}";
        imgA.href = listing_url.replace(/9999/, thisID);
    }
    

    感谢@MikeLee: Get javascript variable's value in Django url template tag

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 2011-03-04
      • 1970-01-01
      • 2015-02-02
      • 2014-03-04
      • 1970-01-01
      • 2018-04-12
      • 2015-06-22
      • 2012-09-27
      相关资源
      最近更新 更多