Q-bart
Q-bart

Reputation: 1591

How can I pass the same context from two views, Django?

I have three templates:

  1. Base_template
  2. first_template
  3. second_template

first_template and second_template extend base_template. So, they have the same aside bar. And I need to pass the same context to these templates. Of course, I can make it once in the first view and then in the second. But, to my mind, it will not a good practice. Or, I can make a function in utils.py and add it to context_processors, but then It will be passed to all website.

What should I do? Give me an advice, please.

Thanks.

Upvotes: 0

Views: 151

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You have a few options:

  1. You can use sessions - add the context to the session and then render it directly from the session in the template.

  2. Create a custom context processor; and simply ignore the variables in the other templates.

  3. Create a base view class, and then inherit from it in your other views. This way, your context is only defined once.

  4. Create a custom decorator that injects the context into the response, then decorate the methods (or classes) where you need it.

Of these four, 2 and 3 are the better ones; 4 will also work but requires that you understand how decorators work. The sessions I just added in there in case this was a temporary requirement - otherwise you should really ignore sessions and look at the others.

Upvotes: 2

Related Questions