S
S
Sazoks2021-12-19 16:22:53
Django
Sazoks, 2021-12-19 16:22:53

Django Middleware | How to deal with implicitness when adding objects to the template context through middleware?

I am new to Django. Faced such task. In the header of the site there is a drop-down menu of services. A service is a model for a database. I take a list of all services, send them to the template, the template engine builds a menu for these services and sends the finished html to the front.

I thought that since there is a site header on every page, and writing a request in each controller to receive all services and add them to the context is not a noble thing, I’ll write a middleware layer that will receive all services with each request and add them into the context (if anything, I used this f-th in context_processors, and not in the middleware itself).

The problem is that now, for example, the service page controller function looks like this:

def services(request: HttpRequest) -> HttpResponse:
    """
    Функция-контроллер страницы услуг.

    :param request: Объект запроса.
    :return: Объект ответа со страницей услуг.
    """

    context = {}

    return render(request=request,
                  template_name='services/services.html',
                  context=context)

Those. let's say I open my code in a month, I'll have a look, but my services page does not return any services! Very strange. This is where my confusion lies, because of my inexperience I don’t know what is good and what is bad.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-12-19
@Sazoks

For the purpose you describe, either a context processor or a view mixin is used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question