I think since i am adding marketing_message in templates of views.py thats why my context is displaying message only at index.py... i want to display my message in every page of my app.
middleware.py
from .models import MarketingMessage from django.utils.deprecation import MiddlewareMixin
class DisplayMarketing(MiddlewareMixin):
def __init__(self, get_response):
self.get_response = get_response
def process_request(self, request):
print("something")
try:
request.session['marketing_message'] = MarketingMessage.objects.all()[0].message
except:
request.session['marketing_message'] = False
settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'marketing.middleware.DisplayMarketing',
]
added it in views.py
def index(request):
products = Product.objects.all()
marketing_message = MarketingMessage.objects.all()[0]
context = {'products':products,'marketing_message':marketing_message}
return render(request,'pro/index.html',context)
base.html
{% if marketing_message %}
<div class="alert alert-success alert-dismissible alert-top-message" role="alert">
<h3>
{{ marketing_message.message|safe }}
</h3>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
index.html--
{% extends "pro/base.html" %}
{% load static %}
{% block head_title %}
Home||
{% endblock %}
{% block content %}
<div class="container">
<div class="row">
{% for product in products %}
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
{% if product.productimage_set.all %}
{% for item in product.productimage_set.all %}
{% if item.featured %}
<div style="width:200px;
height:200px;
background-image:URL('{{ MEDIA_URL }}{{ item.image.url }}');
background-repeat:no-repeat;
background-size: cover;
background-position:center;
margin:0 auto;">
</div>
<!-- <img class="img-responsive" src="{{ MEDIA_URL }}{{ item.image.url }}" > -->
{% endif %}
{% endfor %}
{% else %}
<img src="{% static '/download.svg' %}" class="img-responsive" />
{% endif %}
<div class="caption">
<a href="{{ product.get_absolute_url }}"><h3>{{ product.title }}</h3></a>
<p>{{ product.description|truncatewords:15 }}</p>
<p><a href="{{ product.get_absolute_url }}" class="btn btn-primary" role="button">View</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}