M
M
MalekBV2019-09-04 11:04:28
Django
MalekBV, 2019-09-04 11:04:28

Django. How to display data from another foreignKey model in html?

Hello, I have a Model Tag and an Anime model
. Through a foreign key, I connected Tag with Anime, but I need to display all the tags in the place where I loop through anime
anime.tag does not work, since there is no such attribute in the model itself, how to display all tags?
Models.py:

class Anime(models.Model):
    title = models.CharField("Аниме", max_length = 50)
    description = models.TextField("Описание")
    picture = models.ImageField(upload_to='images/', blank = True, null = True, verbose_name = "Картинка")
    pub_date = models.DateTimeField("Дата выхода записи")
    pub_date_post = models.IntegerField("Дата выхода Аниме", default = 0)
    like = models.IntegerField("Лайков", default = 0)

class Tag(models.Model):
    name = models.CharField("Тэг", max_length = 30)
    animes = models.ForeignKey(Anime, on_delete = models.CASCADE, blank = True, null=True)

HTML template:
{% block content %}
<div class="wrapper">
  <div class="container">
    <h1 class="list">ТОП АНИМЕ</h1>
    <div class="row">
        {% for a in anime %}
          <div class="col-4 anime-top mb-5">
            <img src="{{ a.picture.url }}" alt="picture" class="anime-picture">
            <h5 class="anime-title">{{ a.title }}</h5>
            <p>Жанры: {{ a.tag }}</p> <--- Здесь проблема
            <p><i>Год выпуска: {{ a.pub_date_post }}</i></p>
            <p><a href="addlikes/{{ a.id }}" id="like-one-time"> <i class="far fa-heart"></i> </a>{{ a.like }}</p>
          </div>
        {% endfor %}
    </div>
  </div>
</div>
{% endblock %}

In the loop, anime is a variable from view
anime = Anime.objects.all()
return render(request, "animeapp/homePage.html", {"anime": anime})

In the template, paragraph genres, you need to display all the tags, how to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JRazor, 2019-09-04
@JRazor

Where is related_name ? What are you referring to anyway? How is the base supposed to understand what you want?
You go to Tag, in the animes field you add related_name='tags', and then when you call a.tags you get all the tags. Don't forget to do the migration
Then you go to the view:
Then into the template:

{% for a in anime %}
     {% for tag in a.tags %}
          {{ tag }}
     {% endfor %}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question