[PYTHON] Show Django ManyToManyField in Template

Introduction

In this article, I will write how to display what is connected by ManyToManyField in Template.

Model confirmation

Let's check the model first.

models.py


class Kadai(models.Model):
    class Meta:
        verbose_name = 'Task'
        verbose_name_plural = 'Task'

    kadai_name = models.CharField(
        verbose_name='Issue name',
        max_length=100,
        unique=True,
    )

    category_number = models.IntegerField(
        verbose_name='Number of issue categories',
        default=0,
    )

    kadai_thumbnail = models.ImageField(
        verbose_name='Thumbnail image',
        upload_to='media',
    )

    def __str__(self):
        return self.kadai_name


class KadaiCategory(models.Model):
    class Meta:
        verbose_name = 'Issue category'
        verbose_name_plural = 'Issue category'

    kadai_name = models.ManyToManyField(Kadai)

    category_name = models.CharField(
        verbose_name='Category name',
        max_length=100,
        unique=True
    )

    kadai_number = models.IntegerField(
        verbose_name='Number of tasks',
        default=0
    )

    category_thumbnail = models.ImageField(
        verbose_name='Thumbnail image',
        upload_to='media',
    )

    def __str__(self):
        return self.category_name

Check HTML file

This is the big picture, but it's long, so I'll shorten it a little.

models.py


class Kadai(models.Model):
    class Meta:
        verbose_name = 'Task'
        verbose_name_plural = 'Task'

    kadai_name = models.CharField(
        verbose_name='Issue name',
        max_length=100,
        unique=True,
    )

    .
    .
    .

    def __str__(self):
        return self.kadai_name


class KadaiCategory(models.Model):
    class Meta:
        verbose_name = 'Issue category'
        verbose_name_plural = 'Issue category'

    kadai_name = models.ManyToManyField(Kadai)

    category_name = models.CharField(
        verbose_name='Category name',
        max_length=100,
        unique=True
    )

    .
    .
    .

    def __str__(self):
        return self.category_name

This makes it a little easier to see. For the moment, the "Kadai" class has some challenges, and the "Kadai Category" class has several categories. In other words, because it is "many-to-many", I am using ManyToManyField. Now let's look at the Template. This HTML file is connected to "Kadai Category".

kadai_category.html


{% for category in object_list %}
   <div class="col-4 one-card">
        <div class="card" style="width: 18rem;">
             <img src="{{ category.category_thumbnail.url }}" height="300" alt="This is a thumbnail image.">
             <div class="card-body">
                  <h5 class="card-title">{{ category.category_name }}</h5>
                  <p class="card-text">Check your skills and improve your skills!</p>
                  <p>/{{ category.kadai_number }}</p>
                  <a href="#" class="btn btn-primary">Let's Challenge</a>
            </div>
       </div>
   </div>
{% endfor %}

In this state, it is only displaying what is written in Model, and it is not possible to display the model of the "Kadai" class connected by ManyToManyField. So how can you display the "Kadai" class models that are connected by ManyToManyFielf? The answer is this.

kadai_category.html


{% for kadai in category.kadai_name.all %}
   <p>{{ kadai.kadai_name }}</p>
{% endfor %}

Let's take a look at the big picture.

kadai_category.html


{% for category in object_list %}
   <div class="col-4 one-card">
        <div class="card" style="width: 18rem;">
             <img src="{{ category.category_thumbnail.url }}" height="300" alt="This is a thumbnail image.">
             <div class="card-body">
                  <h5 class="card-title">{{ category.category_name }}</h5>
                  <p class="card-text">Check your skills and improve your skills!</p>
                  <p>/{{ category.kadai_number }}</p>
                 #Add here
                 {% for kadai in category.kadai_name.all %}
                    <p>{{ kadai.kadai_name }}</p>
                 {% endfor %}
                  <a href="#" class="btn btn-primary">Let's Challenge</a>
            </div>
       </div>
   </div>
{% endfor %}

I will explain how to write it. Please understand while looking at the big picture above.

{%for counter variable (any name is acceptable) in the counter variable part of a large for statement.Variable names connected by ManyToManyField.all %}
   <p>{{Counter variable.Variable of the model you want to load after connecting with ManyToManyField}}</p>
{% endfor %}

Finally

I don't know if it's well communicated, but please compare and reflect it in your project.

Recommended Posts

Show Django ManyToManyField in Template
Django # 2 (template)
Django HTML Template # 2
Models in Django
(Note) Template file search order in Django
Django Template notes
Django Template Tips
Forms in Django
Specify the view URL in your Django template
Django template file organization
Show pyramids in Python
Model changes in Django
Show decimal point in Python
Performance optimization in Django 3.xx
PHP var_dump in Django templates
Handle constants in Django templates
Set the DateTime type output format in your Django template
Implement follow functionality in Django
Output table structure in Django
Template Method pattern in Java
(Note) Django in Vagrant environment
Template registration from Django Bootstrap
Create an easy-to-use follow model in Django using ManyToManyField through
reload in django shell with ipython
[Python] Show multiple windows in Tkinter
Set placeholders in input fields in Django
Dynamically add form fields in Django
Show axes as percentages in Matplotlib
Errors related to memcached in django
Implementation of login function in Django
Register your Django application in your project
Write foreign key constraints in Django
Get parameter values ​​in Django templates
Make a filter with a django template
The meaning of ".object" in Django
Deploy Django in 3 minutes using docker-compose
Pin factory_boy seed value in Django
GraphQL API with graphene_django in Django
Like button implementation in Django + Ajax
Get the query string (query string) in Django
Create a LINE Bot in Django