I am working on a Django project where admin can upload a hero banner to the site and can also upload a notification on the home page of the site. So I made listviews for listing the two HeroListView and NotificationListView for that. But the second one is not appearing in the page. Please tell me how to solve this issue.
This is the models.py file
from django.db import models
class Hero(models.Model):
image = models.ImageField(upload_to="heros/")
class Notification(models.Model):
notification = models.CharField(max_length=200)
This is the views.py file.
from django.views.generic import ListView
from .models import Hero, Notification
class HeroListView(ListView):
model = Hero
template_name = "home.html"
context_object_name = "hero_list"
class NoticficationListView(ListView):
model = Notification
template_name = "home.html"
context_object_name = "notification_list"
this is the app/urls.py file
from django.urls import path
from .views import HeroListView, NoticficationListView
urlpatterns = [
path("", HeroListView.as_view(), name="home"),
path("", NoticficationListView.as_view(), name="home"),
]
this is the project/urls.py file
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("heros.urls")),
path("", include("products.urls")),
] static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{% extends '_base.html' %}
{% block title %}Home{% endblock title %}
{% block content %}
{% load static %}
<div >
<div id="carouselExampleControls" data-bs-ride="carousel">
<div >
<div >
<img src="{% static 'images/hero2.jpg' %}" alt="..." style="max-height: 400px;">
</div>
{% for hero in hero_list %}
<div >
<img src="{{ hero.image.url }}" alt="..." style="max-height: 400px;">
</div>
{% endfor %}
</div>
<button type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span aria-hidden="true"></span>
<span >Previous</span>
</button>
<button type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span aria-hidden="true"></span>
<span >Next</span>
</button>
</div>
<div >
{% for note in notification.list %}
<p>{{ note.notification }}</p>
{% endfor %}
</div>
</div>
{% endblock content %}
please tell me how to solve this issue.
CodePudding user response:
You can do it this way
class HeroListView(ListView):
model = Hero
template_name = "home.html"
def get_context_data(self):
context = super(HeroListView, self).get_context_data()
context['hero_list'] = Hero.objects.all()
context['notification_list'] = Notification.objects.all()
return context
You can't access two or multiple views at the same time, so in your case, you can remove NoticficationListView
and use only HeroListView
to render both hero_list
and notification_list