Home > database >  Need help in displaying items from ManyToMany relation in Django template
Need help in displaying items from ManyToMany relation in Django template

Time:06-12

I am struggling with displaying items from manytomany field in my html file.

models.py

class Ingredients(models.Model):
    name = models.CharField('Nazwa', max_length = 100)
    ingredient_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)


class ShoppingList(models.Model):
    name = models.CharField('Nazwa', max_length = 100)
    status = models.BooleanField(default = False)
    last_updated = models.DateTimeField('Ostatnia aktualizacja', auto_now=True)
    publish = models.DateTimeField('Stworzono', default=timezone.now)
    ingredient_list = models.ManyToManyField(Ingredients, related_name='shopping_list')
    slug = models.SlugField(unique=True, blank=True, max_length=254)

views.py

class HomePageView(TemplateView):
    template_name = "homepage.html"
    
    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)

        shopping_list = ShoppingList.objects.all()
        context['shopping_list'] = shopping_list
        return context

homepage.html

{% for list in shopping_list.ingredient_list.all %}
    <div  id="list-{{list.id}}" role="tabpanel" aria-labelledby="list-{{list.id}}-tab">{{list.name}}</div>
{% endfor %}

Any help on how to properly display items in my template file would be appreciated.

CodePudding user response:

A many too many fields you have to do a nested for loop. So say you had something like this in your views.

shoping_list = shoppinglist.objects.all()
context = {"shopping_list": shopping_list}

HTML

{% for i in shopping_list %}
  {{i.name}} <-- displays name from shopping list model
 {% for ingredient in i.ingredient_list.all%}
   {{ingredient.name}}
   {{ingredient.ingredient_category}}

This is how you would access the items.

  • Related