Django redirect()与anchor(#)参数 [英] Django redirect() with anchor (#) parameters
问题描述
我目前正在使用Django的redirect()方法来构造要重定向到的URL。我不想硬编码URL,所以我一直这样做:
return redirect('main.views这个需要我的东西,如:
$ b
$ b
/ home / test-123 /
但是我为特定网址添加了一些客户端跟踪,因此我想使用锚点最终确定像首次用户访问这样的事情:
/ home / test-123 /#first
在redirect()方法中对上述URL进行硬编码,是否有更优雅的替代方法,将锚点附加到我构造的URL的末尾?
谢谢,
G
redirect()
接受URL ,您可以使用 reverse( )
获得一个并附加哈希部分:
from django.core.urlresolvers import reverse
return redirect(reverse('main.views.home',kwargs = {'home_slug':slug})+'#first')
#或字符串格式化
返回重定向'{}#first'.format(reverse('main.views.home',kwargs = {'home_slug':slug})))
另外,还有一个快捷方式 django.shortcuts.resolve_url
,其作用如下:
'{}#first'.format(resolve_url('main.views.home',home_slug = slug))
I'm currently using Django's redirect() method to construct URLs to redirect to. I don't want to hardcode the URL so I've been doing it like this:
return redirect('main.views.home', home_slug=slug)
Which takes me to something like:
/home/test-123/
But I'm adding some client-side tracking for specific URLs so I wanted to use anchors on the end to identify things like first-time user visits like this:
/home/test-123/#first
Short of hardcoding the above URL in the redirect() method, is there a more elegant alternative to append the anchor to the end of my constructed URLs?
Thanks, G
redirect()
accepts URL, you could use reverse()
to get one and appending hash part:
from django.core.urlresolvers import reverse
return redirect(reverse('main.views.home', kwargs={'home_slug':slug}) + '#first')
# or string formatting
return redirect('{}#first'.format(reverse('main.views.home', kwargs={'home_slug':slug})))
Also, there is a shortcut django.shortcuts.resolve_url
which works like:
'{}#first'.format(resolve_url('main.views.home', home_slug=slug))
这篇关于Django redirect()与anchor(#)参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!