【问题标题】:django - using urls in templates from variable in viewsdjango - 在视图中的变量中使用模板中的 url
【发布时间】:2018-04-26 11:40:26
【问题描述】:

假设我有这个观点

def foo_bar(request):

    context = {
        'url': 'app_name:foo"
    }

    return render(request, 'template.html', context)

在模板中,我想要这样的东西:

<form action="{% url {{ url }} %}">
...
</form>

但是,它会抛出 ID expected

有没有办法让它工作?

【问题讨论】:

  • 这不可能显示“预期 ID”。请显示您正在使用的实际代码和确切的错误消息。
  • 不要在模板标签中使用{{ }}。请改用{% url url %}

标签: django templates url views


【解决方案1】:

也许更好的方法是使用django reverse

from django.urls import reverse

def foo_bar(request):

    context = {
        'url': reverse('app_name:foo'),
    }

    return render(request, 'template.html', context)

在模板中简单:

<form action="{{ url }}">
...
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 2018-07-01
    • 2016-05-09
    • 2015-02-02
    • 2015-06-21
    • 1970-01-01
    • 2020-01-08
    • 2021-02-15
    相关资源
    最近更新 更多