Absolute URLs (including domain name)

4 views
Skip to first unread message

Karish

unread,
Sep 26, 2008, 12:40:02 AM9/26/08
to Django users
I am using {{ MEDIA_URL }} in my templates for images, CSS and JS. For
example, {{ MEDIA_URL }}img/abc.gif

I want to do something similar when I need absolute URLs, and I was
wondering what approaches exist. For example, I could define SITE_URL
= 'http://www.domain.com/' in settings.py, and then refer to that
(after setting up a context processor). Unfortunately, I have to strip
off the trailing slash from SITE_URL, so that I can do things like
this:

{{ SITE_URL }}{% url 'view_path' %}

(the url tag includes a slash at the beginning, so SITE_URL can't end
in a slash)

Thanks!


bruno desthuilliers

unread,
Sep 26, 2008, 4:41:23 AM9/26/08
to Django users
On 26 sep, 06:40, Karish <tshi...@gmail.com> wrote:
> I am using {{ MEDIA_URL }} in my templates for images, CSS and JS. For
> example, {{ MEDIA_URL }}img/abc.gif
>
> I want to do something similar when I need absolute URLs, and I was
> wondering what approaches exist.

http://docs.djangoproject.com/en/dev/ref/contrib/sites/#getting-the-current-domain-for-full-urls

Then you have a couple options availables:
- add a context processor (if there isn't already one in the Sites
app) to inject the current site domain name (with or without trailing
slash !-) in your context

- or write a custom filter that adds the domain name to your urls, ie:

{% url 'view_name'|with_domain %}


@register.filter
def with_domain(url):
# XXX : should check if the url already has a domain before
return 'http://%s%s' % (Site.objects.get_current().domain, url)

- or write a custom template tag that replaces {% url %}


My 2 cents...
Reply all
Reply to author
Forward
0 new messages