0

Is it possible to have the variables of a context block accessible to more than one view? Can one create "constants" in Django 'views.py'?

I have two pages: 'index.html' and 'post_list.html'. They both use the model 'Post', but the two pages aren't identical. So the DRY principle went out the window.

A quick search dug out some older questions about writing the variables into 'settings.py' or writing a block of code like def settings...

How is it done with Django 3.x?

YCode
  • 1,192
  • 1
  • 12
  • 28
  • 2
    Yes, these are *context processors*: https://docs.djangoproject.com/en/3.2/topics/templates/#context-processors – Willem Van Onsem Jul 15 '21 at 20:46
  • I read that part of Django docs, but not sure I get it. Are you saying: Writing the variables into 'settings.py' is the way to go? I thought the 'context' block is used in views. – YCode Jul 15 '21 at 21:10
  • 1
    @YCode No you can write code which is loaded by the settings and injected into the context of every page. That way you can get those variables in any template. – markwalker_ Jul 15 '21 at 21:25
  • @markwalker_ Guess I got it wrong. So the functions inside class-based models are all context processors. Perhaps I should re-phrase my question: How do I set up a 'context' block, like `context = { 'author' : author, 'book' : book,}` -- that gets used by several context processors (in several views)? Or is this question totally off? – YCode Jul 16 '21 at 00:07
  • 1
    @YCode if I only wanted that context in certain views, because I use class based views, I'd do that with a mixin or base view from which the others can inherit. – markwalker_ Jul 16 '21 at 08:56
  • That's what I was getting at. Thanks! If you make it an answer, I'll accept it for others to see. – YCode Jul 16 '21 at 14:34

0 Answers0