K
K
Karwag2021-06-12 14:42:32
Django
Karwag, 2021-06-12 14:42:32

How to display all data from the database in templates on the main page?

I need to bring all the title and executor of the model from the database to the main page. They are passed to the templates_song.html template, and from there to index.html. When I tried, I got 5 titles in one object, 11 identical templates and an error 'Song' object is not iterable. I would be grateful if someone could explain what I need to fix

models.py

from django.db import models


class Tool(models.Model):
    name = models.CharField(verbose_name='Инструмент', max_length=255)
    slug = models.SlugField(unique=True)

    class Meta:
        verbose_name_plural = "Музыкальные инструменты"

    def __str__(self):
        return self.name


class Song(models.Model):
    title = models.CharField(max_length=255, verbose_name='Название')
    executor = models.CharField(max_length=255, verbose_name='Исполнитель')
    img_executor = models.ImageField(verbose_name="Изображение группы", blank=True)
    musical_instrument = models.ForeignKey(Tool, verbose_name='Инструмент', on_delete=models.CASCADE)
    chords = models.CharField(max_length=255, verbose_name="Аккорды")
    tabs_chords1 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords1', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords2 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords2', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords3 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords3', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords4 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords4', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords5 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords5', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords6 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords6', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords7 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords7', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords8 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords8', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords9 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords9', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords10 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords10', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords11 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords11', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    tabs_chords12 = models.ForeignKey('GuitarTabs', related_name='related_tabs_chords12', verbose_name='Априкатура', on_delete=models.CASCADE, blank=True, null=True)
    hit = models.ForeignKey('GuitarHit', related_name='related_hit', verbose_name="Бой", on_delete=models.CASCADE)
    text = models.TextField(verbose_name='Текст песни')

    class Meta:
        verbose_name_plural = "Песни"

    def __str__(self):
        return "{} : {}".format(self.executor, self.title)


class GuitarTabs(models.Model):
    title = models.CharField(max_length=255, verbose_name='Название')
    slug = models.SlugField(unique=True)
    tabs = models.ImageField(verbose_name="Табы", blank=True)

    class Meta:
        verbose_name_plural = "Гитарные априкатуры"

    def __str__(self):
        return self.title


class GuitarHit(models.Model):
    title = models.CharField(max_length=255, verbose_name='Название')
    slug = models.SlugField(unique=True)
    hit = models.CharField(max_length=255, verbose_name="Бой")

    class Meta:
        verbose_name_plural = "Гитарные бои"

    def __str__(self):
        return "{} : {}".format(self.title, self.hit)


views.py
from django.shortcuts import render
from django.views.generic import DetailView
from .models import *


class HomeDetailViews(DetailView):
    model = Song
    queryset = Song.objects.all()
    template_name = "templates_song.html"
    context_object_name = 'songs'


urls.py
from django.urls import path, include
from .views import *

urlpatterns = [
    path('first-post/<int:pk>/', HomeDetailViews.as_view(), name='homeviews'),
]


templates_song.html
{% extends 'index.html' %}

{%block navigate%}
 <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container px-4 px-lg-5">
                <a class="navbar-brand" href="#!">GuiratPub</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav me-auto mb-2 mb-lg-0 ms-lg-4">
                        <li class="nav-item"><a class="nav-link active" aria-current="page" href="#!">Главная</a></li>
                        <li class="nav-item"><a class="nav-link" href="#!">Популярные</a></li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Категории</a>
                            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                                <li><a class="dropdown-item" href="#!">Зарубежные</a></li>
                                <li><hr class="dropdown-divider" /></li>
                                <li><a class="dropdown-item" href="#!">Класические</a></li>
                                <li><a class="dropdown-item" href="#!">Новые</a></li>
                            </ul>
                        </li>
                    </ul>
                    <form class="d-flex">
                        <button class="btn btn-outline-dark" type="submit">
                            Аккорды
                        </button>
                    </form>
                </div>
            </div>
        </nav>
{%endblock%}


{%block content%}
   {%for song in songs%}
                    <div class="col mb-5">
                        <div class="card h-100">
                            <!-- Product image-->
                            <img class="card-img-top" src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg" alt="..." />
                            <!-- Product details-->
                            <div class="card-body p-4">
                                <div class="text-center">
                                    <!-- Product name-->
                                    <h5 class="fw-bolder">
                                           {{song.title}}
                                    </h5>
                                    <!-- Product price-->
                                   {{song.executor}}
                                </div>
                            </div>
                            <!-- Product actions-->
                            <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
                                <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">Просмотреть</a></div>
                            </div>
                        </div>
                    </div>
{%endfor%}
{%endblock%}


index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>GuitarPub</title>
        <!-- Favicon-->
        <link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
        <!-- Bootstrap icons-->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" rel="stylesheet" />
        <!-- Core theme CSS (includes Bootstrap)-->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    </head>
    <body>
        <!-- Navigation-->
       {%block navigate%}
        {%endblock%}
        <!-- Header-->
        <header class="bg-dark py-5">
            <div class="container px-4 px-lg-5 my-5">
                <div class="text-center text-white">
                    <h1 class="display-4 fw-bolder">GuitarPub</h1>
                    <p class="lead fw-normal text-white-50 mb-0">Аккорды и табы песен</p>
                </div>
            </div>
        </header>
        <!-- Section-->
        <section class="py-5">
            <div class="container px-4 px-lg-5 mt-5">
                <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">

                    {%block content%}
                    {%endblock%}

                </div>
            </div>
        </section>
        <!-- Footer-->
        <footer class="py-5 bg-dark">
            <div class="container"><p class="m-0 text-center text-white">Сайт сделан при поддержки Вадима 2021</p></div>
        </footer>
        <!-- Bootstrap core JS-->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
        <!-- Core theme JS-->
        <script src="js/scripts.js"></script>
    </body>
</html>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2021-06-12
@deepblack

DetailView to display one entry.
There is also documentation and introductory lessons on the Jungi website

K
Karwag, 2021-06-12
@Karwag

Already corrected. I didn’t notice that I accidentally wrote DetailView instead of ListView. Thanks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question