1Up
1Up

Reputation: 1044

Current way to get Home URL (Domain) in Django Template?

This is so simple, yet it seems that its not provided.

Basically, if my site is...

Or a non-root install like

...I would think django would know this and have a constant available in templates.

The solutions I find involve:

  1. Set it up in settings.py with SITE_URL =
  2. Reference settings.py in a view.
  3. Finally access it in the template with {{ SITE_URL }} or something.

Not very D.R.Y.

Not to sound spoiled, but doesn't django provide the {{ GET_ME_THE_ROOT_URL }} reference?

Sorry, django has trained me to expect goodies like this.

Just sayin' if I was writing a framework that would be the first thing I do, besides putting a small fridge beside my desk full of hotpockets and a microwave a safe but close distance away.

Upvotes: 9

Views: 8154

Answers (2)

Animesh Sharma
Animesh Sharma

Reputation: 3386

Ha! Nice question.

Let's break down your problem. You want some data to be available across all the templates available in your project. And also, you want to provide the value once and not repeat it across views.

Template Context Processors is the thing you are looking for. In your settings.py file, add a new context_processor to the list of TEMPLATE_CONTEXT_PROCESSORS.

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
    "django.contrib.messages.context_processors.messages",
    "your_app.context_processors.root_url"
)

Then, inside your_app, create a file named context_processors.py. This file will contain the following code.

from django.conf import settings

def root_url(request):
    """
    Pass your root_url from the settings.py
    """
    return {'SITE_URL': settings.ROOT_URL_YOU_WANT_TO_MENTION}

And, in each of your templates, you'll have a {{SITE_URL}} present in the context depending on the value you provide to ROOT_URL_YOU_WANT_TO_MENTION in your settings.py file.

Django sure spoils everyone. But provides the mechanisms to keep you spoilt.

Hope this solves your problem.

Upvotes: 10

Andrew Konoff
Andrew Konoff

Reputation: 571

If you're rendering the template from a request, you can just name your root view, then refer to it with the url tag:

In your root urls.py:

url(r'^$', HomePageView.as_view(), name='home'),

In template.html:

click <a href="{% url 'home' %}">here</a> 

More good info over in the django docs: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#url

Upvotes: 4

Related Questions