Evgenii Legotckoi
Sept. 27, 2016, 12:06 a.m.

Django - Tutorial 010. Getting the variables in the template file in Django from settings.py

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.

  1. 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:

  1. home/
  2. migrations/
  3. templates/
  4. templatetags/
  5. __init__.py
  6. home_extras.py
  7. __init__.py
  8. admin.py
  9. apps.py
  10. models.py
  11. sitemap.py
  12. tests.py
  13. urls.py
  14. views.py

And now look home_extras.py contents.

  1. from django import template
  2. from django.conf import settings
  3.  
  4. register = template.Library()
  5.  
  6.  
  7. @register.simple_tag
  8. def get_attribute(name):
  9. 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.

  1. {% load home_extras %}
  2. {% get_attribute 'SITE_URL' %}"

For Django I recommend VDS-server of Timeweb hoster .

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html