N
N
nekritik2015-09-24 04:16:19
Django
nekritik, 2015-09-24 04:16:19

Django: how to pass same data to different views?

Sorry for the uninformative title, it's hard to convey the whole essence of the issue in one line.
I recently started learning Django and to hone my knowledge, I'm trying to create a small engine for a certain system, or, as it's fashionable to say now: I'm creating a web application.
Now I'll get to the point. Each user has a "balance" in the system and it must be constantly visible to authorized users, regardless of which page the user is on.
For example, we have 2 views (view), let's call them buy and sell (buy and sell). Each view executes a certain code, "calls" the template (template) and passes various data to it (the template). I need the user's balance to be included in the templates without fail. How can I do that? The first thing that comes to mind is to call a function for each view that would return the balance. Like this:

def buy(request):
    balance = get_balance();
    return render_to_response("buy.html",{'balance':balance});
def sell(request):
    balance = get_balance();
    return render_to_response("sell.html",{'balance':balance});

This method can be quite efficient, but somehow it looks wrong and ugly. How can you solve this problem? On the Web, I found something that, in theory, can solve the problem - middleware , but I did not find much use cases on this topic on the Internet.
Please advise how best to solve the problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2015-09-24
@nekritik

Turn on the middleware to inject the request into the template

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',

in the template we request information about the user
<h2>{{ request.user.get_ballance() }}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question