How to make something appear on every page in Django?

I'm curious how best to deal with the appearance of something on each page or on multiple pages without having to manually assign data to each page:

# views.py

def page0(request):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(request.user),
        },
        context_instance=RequestContext(request)
    )

def page1(request):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(request.user),
        },
        context_instance=RequestContext(request)
    )
...
def page9(request):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(request.user),
        },
        context_instance=RequestContext(request)
    )

Now I can come up with several ways to do this, including writing my own Context, or perhaps some middleware, and, of course, copy / paste this assignment localityto each page ... I'm just not sure the best way to do this. I'm sure this is not the last though.

+3
source share
4 answers

. , , , RequestContext. .

, , .

+16

:

base.html, :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
<div id="sidebar">
    {% block sidebar %}
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/blog/">Blog</a></li>
    </ul>
    {% endblock %}
</div>

<div id="content">
    {% block content %}{% endblock %}
</div>
</body>
</html>

, , :

{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}

http://docs.djangoproject.com/en/dev/topics/templates/#id1

.

+3

Middleware - , .

+2

, , :

def foobar(req):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(req.user),
        },
        context_instance=RequestContext(req)
    )

put it in some module myfunand return myfun.foobar(request)wherever it is needed. You'll probably need a few more arguments, but while it’s not so simple, it’s easier to define middleware using OOP, etc.

0
source

Source: https://habr.com/ru/post/1727178/


All Articles