0

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">&times;</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 %}
Avi Kumar
  • 21
  • 1
  • 6

1 Answers1

0

This means you either have to pass the marketing message on every view.

Or you could also create a custom templatetag

from django import template

register = template.Library()

@register.simple_tag
def marketing_message():
     return MarketingMessage.objects.all()[0]

And then load the tag in the html and display the result.

EDIT:

To have the message on every page either you include the message in your base.html and extend the other templates from base or you have to import and use the templatetag in every template

EDIT 2: Usage in base.html

Assuming the above code is in poll_extra.py and you have the following structure where polls your apps name is

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py

the base.html needs:

{% load poll_extras %}
{% marketing_message %}

the first line loads the tag(s) and the second is the tag which returns the message, it is called by the name of the python function

this is all described in the official documentation

Edit: using Middleware from the documentation about middleware

class SimpleMiddleware:
def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.

    response = self.get_response(request)

    # Code to be executed for each request/response after
    # the view is called.

    return response

then your middleware should adjust the context of the response after (or before, not sure if it matters in your case) the view is called

Also check out this answer maybe you try to access the value the wrong way?

bb4L
  • 899
  • 5
  • 16