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.
1
try to print the allSideAds to make sure it exist, if you are sure you have imported the SideBarAd and there is objects, try
allSideAds= list(SideBarAd.objects.all())
random_sideAd = random.choice(allSideAds)