In my Django URLs, I have many URL patterns that end with :
在我的Django URL中,我有许多以下结尾的URL模式:
(redirect/(?P<redirect_to>\w+))
Which means that these URLs can be (or not) ending by /redirect/TARGET/
. These URL patterns have other named arguments (mostly one : pk
)
这意味着这些URL可以(或不)以/ redirect / TARGET /结尾。这些URL模式有其他命名参数(主要是一个:pk)
Now, I'd like, in the templates used by these URL patterns, to be able to alter the current page path, by just adding the redirect_to argument, and keeping the other arguments and URL reverse name untouched.
现在,我想在这些URL模式使用的模板中,只需添加redirect_to参数,并保持其他参数和URL反向名称不变,就能够改变当前页面路径。
I was able to get the URL reverse name in the template, by adding resolve(path).url_name
to the current context, and then to use that with the {% url %}
template tag.
通过将resolve(path).url_name添加到当前上下文,然后将其与{%url%}模板标记一起使用,我能够在模板中获取URL反向名称。
I'd like to know if there is any easy way to dynamically add the arguments (from resolve(path).kwargs
) to the URL reverse tag ?
我想知道是否有任何简单的方法可以动态地将参数(从resolve(path).kwargs)添加到URL反向标记中?
1 个解决方案
#1
1
I think you should create a custom tag for this (replacing your {% url %} tag with {% url_redirect "your_new_destination" %}).
我认为你应该为此创建一个自定义标记(用{%url_redirect“your_new_destination”%}替换你的{%url%}标记。
in your_app/templatetags/my_custom_tags.py:
from django.core.urlresolvers import reverse, resolve
@register.simple_tag(takes_context=True)
def url_redirect(context, new_destination):
match = resolve(context.request.path)
match.kwargs['redirect_to'] = new_destination
return reverse(match.url_name, args=match.args, kwargs=match.kwargs)
in your template:
在您的模板中:
{% load my_custom_tags %}
{% url_redirect "your_new_destination" %}
Please note that you need to add 'django.core.context_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS in order for this snippet to work.
请注意,您需要将“django.core.context_processors.request”添加到TEMPLATE_CONTEXT_PROCESSORS,以使此代码段能够正常工作。
#1
1
I think you should create a custom tag for this (replacing your {% url %} tag with {% url_redirect "your_new_destination" %}).
我认为你应该为此创建一个自定义标记(用{%url_redirect“your_new_destination”%}替换你的{%url%}标记。
in your_app/templatetags/my_custom_tags.py:
from django.core.urlresolvers import reverse, resolve
@register.simple_tag(takes_context=True)
def url_redirect(context, new_destination):
match = resolve(context.request.path)
match.kwargs['redirect_to'] = new_destination
return reverse(match.url_name, args=match.args, kwargs=match.kwargs)
in your template:
在您的模板中:
{% load my_custom_tags %}
{% url_redirect "your_new_destination" %}
Please note that you need to add 'django.core.context_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS in order for this snippet to work.
请注意,您需要将“django.core.context_processors.request”添加到TEMPLATE_CONTEXT_PROCESSORS,以使此代码段能够正常工作。