M
M
michael ivanov2015-07-18 15:14:22
Django
michael ivanov, 2015-07-18 15:14:22

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

6 answer(s)
M
michael ivanov, 2015-07-18
@pauchenkov

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} # Возвращаем контекст

Next, in the file where our registered tag and its template should be connected, we write:
That's actually all. In this way I solved the problem. If suddenly the tag does not work for you - check it for errors and if you have no errors in the tag and you are sure of it, then it
is worth checking that:
- there is an __init_.py file in the templatetags directory
- the application is added to INSTALLED_APPS
- if the template tag myapp application is called from the application template otherapp, then in INSTALLED_APPS 'myapp' must be to the left (above) 'otherapp'
- all dependencies required in myapp_tags.py are installed
- make sure that it is possible to import myapp_tags.py itself
python manage.py shell
>>> from myapp.templatetags import myapp_tags

— server restarted after last code change
---
Thank you all and good luck!

S
Stanislav Fateev, 2015-07-18
@svfat

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.

I
Ilya, 2015-07-18
@FireGM

djbook.ru/rel1.7/howto/custom-template-tags.html#i...

P
Postalus, 2015-07-18
@Postalus

Two options:
1. Write your own template tag.
2. Add your context processor.

S
sim3x, 2015-07-18
@sim3x

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

Z
zelsky, 2015-07-18
@zelsky

I agree with Postalus, just write your own template tag and pass everything you need in the view.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question