- Author:
- johnboxall
- Posted:
- May 21, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 7 (after 7 ratings)
The {% url %} templatetag is awesome sometimes it is useful to get the full blown URL with the domain name - for instance for links in emails. The {% absurl %} templatetag mirrors the behaviour of {% url %} but inserts absolute URLs with the domain of the current Site object.
Usage:
{% absurl viewname %}
>>> http://www.example.org/my/view/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import urlparse
from django.template import Library
from django.template.defaulttags import URLNode, url
from django.contrib.sites.models import Site
register = Library()
class AbsoluteURLNode(URLNode):
def render(self, context):
path = super(AbsoluteURLNode, self).render(context)
domain = "http://%s" % Site.objects.get_current().domain
return urlparse.urljoin(domain, path)
def absurl(parser, token, node_cls=AbsoluteURLNode):
"""Just like {% url %} but ads the domain of the current site."""
node_instance = url(parser, token)
return node_cls(view_name=node_instance.view_name,
args=node_instance.args,
kwargs=node_instance.kwargs,
asvar=node_instance.asvar)
absurl = register.tag(absurl)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
It does help to explain that the way to change your current site is from the admin under sites. :) great snippet btw
#
For complete behaviour of url tag, in render method should be
instead of pure return.
#
Note that the snippet in the comment by junckritter works well. Thanks junckritter!
#
I wrote the following, which also takes httpS into account
in your templates you can then use
#
Using query to database just to get domain name of current site is bad idea for me. I prefer gettin domain name value in settings. But thanxx anyway!
#
Please login first before commenting.