In settings.py file in Django we store all the necessary configuration information of our applications, which may include the site's URL or path to certain directories, which store specific files and more information.
And sometimes you want to use these variables in the template, the same site URL. But just to put this constant in the template through {{SITE_URL}} , use this variable will not work. One way of solving this problem is the registration template tag that will perform a specific functionality, for example to take the attribute of the configuration file by its name.
Register template tag
If we are talking about using SITE_URL in the template, the agreement that we have registered this variable in settings.py file.
SITE_URL = 'www.mysite.com'
And then we go into the app, which will register the tag to retrieve the attributes of the settings.py file. In my case, this is the app home . In this application will need to create templatetags catalog and place it in two files: init .py and such home_extras.py .
We obtain the following structure of the application:
home/ migrations/ templates/ templatetags/ __init__.py home_extras.py __init__.py admin.py apps.py models.py sitemap.py tests.py urls.py views.py
And now look home_extras.py contents.
from django import template from django.conf import settings register = template.Library() @register.simple_tag def get_attribute(name): return getattr(settings, name, "")
Using in template
And the use of the template will be even easier. You will need only to load the template tag to expand and take advantage of this tag, giving it the name of the attribute, which want to receive.
{% load home_extras %} {% get_attribute 'SITE_URL' %}"
For Django I recommend VDS-server of Timeweb hoster .