Django Get Absolute URL

neuraminidase7 picture neuraminidase7 · Jul 25, 2013 · Viewed 26.3k times · Source

I want to get absolute url in templates. I can't do with url. It gives me a relative URL. I need to get this:

http://domain.tld/article/post

but Django gives me just

/article/post

I played with settings.py but it didn't work. (debug=false, allowed hosts vs.)

Template code:

{% url 'blog:detail' blog.slug %}

Answer

Kevin Christopher Henry picture Kevin Christopher Henry · Jul 25, 2013

This is easy to do in a view. For example:

from django.core.urlresolvers import reverse

def Home(request): 
    posts = Article.objects.filter(published=True).order_by('-publish') 
    site = Site.objects.get_current()

    c = RequestContext(request, { 
        'posts': [{'post': post,
                   'url': request.build_absolute_uri(reverse('blog:detail', args=[post.slug]))}
                  for post in posts]
        'site': site,
    }) 

    return render_to_response('templates/index.html', c)

Then, in your template, while you're looping with {% for postobj in posts %} you can access postobj.post and postobj.url.

If you want to do this in the template instead you can probably create your own template tag without too much trouble.