Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Get Absolute URL

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 %}
like image 379
neuraminidase7 Avatar asked Jul 25 '13 18:07

neuraminidase7


People also ask

How do I get an absolute URL in Django?

To get the full or absolute URL (with domain) in Python Django, we can use the build_absolute_uri method. to call request. build_absolute_uri with reverse('view_name', args=(obj.pk, ) to get the path of the view with reverse . Then we call “request.

How do I find my Django server URL?

Run the following command to start the Django server. Execute the following URL from the browser to display the domain name of the current URL. The geturl1() function will be called for this URL that will send the domain name to the index. html file.

What is reverse Django?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here.


2 Answers

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.

like image 71
Kevin Christopher Henry Avatar answered Sep 18 '22 18:09

Kevin Christopher Henry


After a long time meeting with Django, I learned a lot of things. For this issue, I created an absolute URL templatetag.

Add this to your template tags, then use like default url tag:

{% absurl 'some-view' with, arguments %}

Here is the Gist for the absolute URL templatetag, you will need to add request object to template_context_processors, otherwise this will not work. To achieve this, open your settings.py and add these following lines:

from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    'django.core.context_processors.request',
)
like image 41
neuraminidase7 Avatar answered Sep 18 '22 18:09

neuraminidase7