Answer the question
In order to leave comments, you need to log in
How to select data from db in django template itself? Or what is the best way to do it?
The bottom line is that I have a sidebar on the site. It needs to get data from the model. The sidebar is connected to every page of the site. I do not understand how to make a selection from the database (mysql) without url and view. I don't quite understand how to implement this. I would be grateful if you could advise. It’s easy for a pro for you, but for a beginner it’s complicated (from this - all the questions.
Answer the question
In order to leave comments, you need to log in
Here is my solution, maybe it will be useful for someone.
The problem was solved by writing a custom tag (your own tag) in django 1.8.2 !
I did it like this:
1) Create in the folder with the APPLICATION (APP, well, that is, in the folder that was created when the startapp command was executed) the templatetags folder .
2) In the templatetags folder, create:
a) An empty __init__.py file (a file that notifies Python that this directory is a Python module)
b) A file with the name of our new tag ( in my case it is called sidebar.py). Some processing will take place in this file! In my case: registering a tag, fetching from the database and returning the context.
3) Open our newly created sidebar.py file and write:
from django import template
from blog.models import RightSidebarWidgets #Импортируем нужные нам модели.
# экземпляр класса, в котором все наши теги будут зарегистрированы
register = template.Library()
# регистрируем наш тег, который будет выводить шаблон right_sidebar.html
@register.inclusion_tag("blog/right_sidebar.html") #В кавычках вводите путь до шаблона! он может быть у каждого свой!
# Создаем сам тег!
def show_sidebar():
widgets = RightSidebarWidgets.objects.all() # Делаем выборку из БД
return {'widgets': widgets} # Возвращаем контекст
python manage.py shell
>>> from myapp.templatetags import myapp_tags
The django template engine does not know anything about the database and it will not work to make a selection from the database using the template engine. It is necessary to pass data to the template through view.
Two options:
1. Write your own template tag.
2. Add your context processor.
A beginner should start reading 2 scoops of django
A beginner should go through https://docs.djangoproject.com/en/1.8/intro/tutorial01/
The
template only shows data
The view only combines data into one set
The model stores and does most of the work
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question