Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django redirect() with anchor (#) parameters

Tags:

django

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

like image 794
GivP Avatar asked Jun 22 '12 23:06

GivP


2 Answers

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))

EDIT for Django 2.0, use: from django.urls import reverse

like image 89
okm Avatar answered Nov 12 '22 20:11

okm


[Only working up until Django 1.8, not functional in Django 1.9+, see comments!]

You can add an anchor into the regular expression in urls.py. Here is an example from a sample forum app which will jump to the desired post in a thread.

views.py

return redirect(post_list, 
    slug=post.thread.slug, 
    page=1, 
    anchor='post_{0}'.format(post.id)
)

urls.py

url(r'^thread/(?P<slug>[-\w]+)/(?P<page>[0-9]+)/#(?P<anchor>[-_\w]+)$', post_list, name='forum_view_thread'),
url(r'^thread/(?P<slug>[-\w]+)/(?P<page>[0-9]+)/$', post_list, name='forum_view_thread'),
url(r'^thread/(?P<slug>[-\w]+)/$', post_list, name='forum_view_thread'),
like image 43
scum Avatar answered Nov 12 '22 19:11

scum