简体   繁体   English

如何将上下文对象作为Django URL模板标记参数传递

[英]How to pass context objects as Django url template tag arguments

In my django project, I have two model classes - Category & Action. 在我的django项目中,我有两个模型类-类别和动作。 Category is the ForeignKey of Action (all Actions fall under a Category). 类别是动作的外键(所有动作都属于类别)。

Within my django templates, I'd like to be able to pass a context object into a {% url %} tag that accepts a string containing the name of a Category as an argument. 在我的django模板中,我希望能够将上下文对象传递到{%url%}标记中,该标记接受包含类别名称作为参数的字符串。 So in a perfect world my django template would have a line like: 因此,在理想世界中,我的django模板将具有以下一行:

<form action="{% url 'actions' {{ category }} %}">

And when submitted, Django would follow the form to a urlpattern like: 提交后,Django将遵循以下形式的urlpattern:

url(r'^(?P<category_name>\\w+)', views.actions, name='actions'),

But unfortunately it doesn't look like I'm able to nest template filters into template tags. 但不幸的是,看起来我无法将模板过滤器嵌套到模板标签中。 What's an alternate way I can reference the ForeignKey of a Django object within a url tag? 我可以在url标记中引用Django对象的ForeignKey的另一种方法是什么? Or perhaps a different way to structure my code? 还是一种不同的方式来构造我的代码?

上下文变量可直接在url templatetag中使用

<form action="{% url 'actions' category_name=category %}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM