I'm trying to get ads to show on the sidebar of my website (in base.html). However the ad isn't displaying.
The code I'm using is:
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
import random
def base(request):
allSideAds=SideBarAd.objects.all()
random_sideAd = random.choice(allSideAds) if allSideAds else None
return render(request, 'base.html', {'random_sideAd': random_sideAd})
models.py
from django.contrib import admin
from django.db import models
from django.urls import reverse
class SideBarAd(models.Model):
AdImage = models.ImageField(help_text='Enter Image Here')
AdLink = models.URLField()
MaxAdViews = models.PositiveBigIntegerField()
AdViews = models.PositiveBigIntegerField()
Approved = models.BooleanField()
def get_absolute_url(self):
return self.AdImage
base.html
{% if random_sideAd %}
<a href="{{ random_sideAd.AdLink }}">
<img src="{{ random_sideAd.AdImage.url }}" alt="Ad Image">
</a>
{% endif %}
When I load a page, the ad that's in my database isn't shown through base.html.
I was able to figure out why this wasn't working. Instead of running this through views.py, I decided to use context_processors.py.
context_processors.py:
import random
from .models import SideBarAd
def sidebar_ad(request):
sidebar_ads = SideBarAd.objects.filter(Approved=True)
sidebar_ad_data = random.choice(sidebar_ads) if sidebar_ads else None
return {'sidebar_ad': sidebar_ad_data}