26π
To meet your initial goal, I do not think the BeforeFilter middle ware is required. What we need is just a template context processor.
Write a context processor as following:
#file: context_processors.py
def sample_context_processor(request):
return {'ss':'ssssssssss'} #or whatever you want to set to variable ss
then add the context processor to TEMPLATE_CONTEXT_PROCESSORS list
#file: settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'myproject.context_processors.sample_context_processor',
)
3π
You need to specify that you accessing request
in the template. If you do just {{ss}}
the variable does not exist since it an attribute of request
(you did request.ss = 'ssssssssss'
, right?). So do {{request.ss}}
in your template and it should work.
- Django GROUP BY strftime date format
- What could cause a Django error when debug=False that isn't there when debug=True
- HTML input textbox in Django admin.py filter
- How to downgrade from Django 1.7 to Django 1.6
- Django- session cookies and sites on multiple ports
1π
The OP asked for how to do this with middleware but I found this question without needing that requirement. The currently accepted answer is outdated and the edit queue is full.
As of Django 1.10, the TEMPLATE_CONTEXT_PROCESSORS
setting has been moved to the context_processors
option of TEMPLATES
.
context_processors
is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context. It defaults to an empty list.
# context_processors.py
def sample_context_processor(request):
return {'key': 'value'}
# settings.py
TEMPLATES = [
{
'OPTIONS': {
'context_processors': [
'myproject.context_processors.sample_context_processor',
],
},
},
]
- How to find out whether a model's column is a foreign key?
- Listing Related Fields in Django ModelAdmin
- Django test database is not created with utf8
- Tracking changes to all models in Django
- Django β Polymorphic Models or one big Model?