如何将变量结果插入Django模板语言的调用中

时间:2019-05-28 09:41:23

标签: python django

在Django中,我尝试进行一个通用的“确认操作”调用,可以轻松地将最终地址传递给该调用,但是在链接中插入变量时遇到了困难:

<a href="{% url 'view_do_confirm_action' 'url view_delete_object object.object_name' %}"> Delete this object </a><br>

如果不清楚,则view_do_confirm_action的参数是用户确认后要遵循的URL。我希望遵循的最终URL链接到此模式:

path('objects/object/<str:object_name>/delete', views.view_delete_object, name='view_delete_object'),

“ URL view_delete_object object.object_name”在正确的时间没有得到解决-有什么建议吗?

谢谢

扫描

2 个答案:

答案 0 :(得分:1)

您无需在Django模板表达式中添加另一个表达式。

您要将一个URL作为参数传递给另一个URL。

代替

<a href="{% url 'view_do_confirm_action' 'url view_delete_object {{ object.object_name }}' %}"> Delete this object </a><br>

{% url view_delete_object object.object_name as the_url %}
<a href="{% url 'view_do_confirm_action' the_url %}"> Delete this object </a><br>

答案 1 :(得分:0)

urls.py

path('<str:object_name>/delete', ViewBarDrinkDetail, name='view_delete_object'),
path('confirm/<str:url_text>', ViewBarDrinkUpdate, name='view_do_confirm_action'),

您的顶部URL view_do_confirm_action使用的是 url_text ,该url_text显然将包含 / ,而这些动态斜杠Django将无法解决您的view_do_confirm_action

解决方案

尝试更改图案:

path('/confirm/<str:object_name>/delete', ViewBarDrinkDetail, name='view_do_confirm_action'),

使用自定义模板标签

@register.simple_tag
def pass_url_to_reverse_name(name, arg_url_name, arg_url_args):

    arg_resolved_url = reverse(arg_url_name, args=[arg_url_args])
    resolved_url = reverse(name, args=[arg_resolved_url])

    return resolved_ur

在模板中像这样使用它:

<a href="{% pass_url_to_reverse_name 'view_do_confirm_action' 'view_delete_object' request.user.id %}"> Delete this object </a>