Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question