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:
SITE_URL =
{{ 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.
In the template, you can use {{ site. domain }} to get the current domain name.
You can do that by using request. META['HTTP_REFERER'] , but it will exist if only your tab previous page was from your website, else there will be no HTTP_REFERER in META dict . So be careful and make sure that you are using . get() notation instead.
The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py . Listing 2-16 shows how to name a project's home page, as well as how to reference this url from a view method or template.
{% 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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With