0

I am trying to display a brand of a bike, but the value shows as None.

Models.py:

class Bike(models.Model):
  item = models.OneToOneField(Item, on_delete=models.CASCADE)
  brand = models.ManyToManyField(Brand, null=True)

class Brand(models.Model):
 name = models.CharField(max_length=20)

and here's my template:

{% for item in items  %}

{{ item.bike.brand.name }} {{ item.title }}

{% endfor %}

I am calling the brand by {{ item.bike.brand.name }} and it displays as None for every Bike

Menor
  • 302
  • 2
  • 14

1 Answers1

1

if your view is like this,

class BikeListView(ListView):
    model = Bike
    template_name = '----.html'

you can call it in your templates as

{% for obj in object_list  %}
{{ obj.field_name in your item model }} 
{% for brand_name in obj.brand.all  %}
{{ brand_name.name }} 
{% endfor %}{% endfor %}
bmons
  • 3,352
  • 2
  • 10
  • 18
  • in my case it would be `{% for item in items %}``{% for bra in item.bike.brand.all %}``{{ bra.name }}``{% endfor %}``{% endfor %}`, thanks – Menor Feb 29 '20 at 04:29
  • Do you have any idea how I would display the same thing but in my django admin page, when I enter bikes table? Currently I have `def __str__(self):return self.item.title` and it shows the title but when I do `self.brand.name` it shows None – Menor Feb 29 '20 at 04:34
  • check this answer https://stackoverflow.com/questions/43894232/displaying-both-sides-of-a-manytomany-relationship-in-django-admin – bmons Feb 29 '20 at 04:39