Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a name to a absolute url in django template?

{% url url_name %} gives a relative name.

How can I do something like {% absolute_url url_name %} so that it returns url with base (including port if present)?

like image 507
eugene Avatar asked Sep 26 '13 09:09

eugene


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.

What is URL reverse in 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. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.

What {{ name }} means in a Django template?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What does form {% URL %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .


1 Answers

There are different solutions. Write your own templatetag and use HttpRequest.build_absolute_uri(location). But another way, and a bit hacky.

<a href="{{ request.scheme }}://{{ request.get_host }}{% url url_name %}">click here</a> 

Edit: So I'm kinda confused this still gets me upvotes. I currently find this really hacky. Writing an own template tags has gotten a lot easier, so hereby the example for your own tag.

from django import template from django.urls import reverse  register = template.Library()  @register.simple_tag(takes_context=True) def abs_url(context, view_name, *args, **kwargs):     # Could add except for KeyError, if rendering the template      # without a request available.     return context['request'].build_absolute_uri(         reverse(view_name, args=args, kwargs=kwargs)     )  @register.filter def as_abs_url(path, request):     return request.build_absolute_uri(path) 

Examples:

<a href='{% abs_url view_name obj.uuid %}'>  {% url view_name obj.uuid as view_url %} <a href='{{ view_url|as_abs_url:request }}'> 
like image 66
Blackeagle52 Avatar answered Nov 04 '22 13:11

Blackeagle52