Value is none when calling out a value of foreign key - python

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

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 %}

Related

Could not parse the remainder:

I saw many questions about this error, but all are distincts and not apply to me, so...
My models.py
# Category
class Category(models.Model):
category_name = models.CharField(max_length=64)
def __str__(self):
return f"{self.category_name}"
# Item
class Item(models.Model):
item_name = models.CharField(max_length=64)
category = models.ForeignKey(Category, on_delete= models.CASCADE, related_name="items_by_category")
price_small = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0)
price_large = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0)
nradd = models.IntegerField(default=0)
def __str__(self):
return f"{self.category} {self.item_name} - Qty.of Adds: {self.nradd} - Price Small: {self.price_small} - Price Large: {self.price_large}"
My views.py
def menu(request):
products = list(Item.objects.all().values().order_by('category'))
categories = list(Category.objects.all().prefetch_related('items_by_category'))
extras = list(Extra.objects.filter(category="T"))
subsextras = list(Extra.objects.filter(category="S"))
context = {
'Products' : products,
'Categories': categories,
'Extras' : extras,
'Subextras' : subsextras
}
return render(request, 'orders/menu.html',context)
First, I'm trying to simply list the categories with the items who belongs to:
My menu.html:
{% extends 'orders/base.html' %}
{% load static %}
{% block title %}
Menu
{% endblock %}
{% block body %}
<ul>
{% for cate in Categories %}
<li>{{ cate.category_name }}</li>
<ul>
{{% for myitem in cate.items_by_category.all %}}
<li>{{ myitem.item_name }}</li>
{{% endfor %}}
</ul>
{% endfor %}
</ul>
{% endblock %}
the error appears in the line:
{{% for myitem in cate.items_by_category.all %}}
Same commands in the shell goes well:
cate = Category.objects.get(category_name="Salads")
cate.items_by_category.all()
Thanks in advance,
It's about Template Language.
Variables look like this: {{ variable }}.
Filters look like this: {{ name|lower }}.
Tags look like this: {% tag %}.
To comment-out part of a line in a template, use the comment syntax:
{# #}
There is no such thing as {{% %}}
So, instead of
{{% for myitem in cate.items_by_category.all %}}
You should use
{% for myitem in cate.items_by_category.all %}
Reference:
https://docs.djangoproject.com/en/3.0/ref/templates/language/
The template tags are sourrounded with {% … %}, not {{% … %}}. So you should rewrite the template to:
{% extends 'orders/base.html' %}
{% load static %}
{% block title %}
Menu
{% endblock %}
{% block body %}
<ul>
{% for cate in Categories %}
<li>{{ cate.category_name }}</li>
<ul>
{% for myitem in cate.items_by_category.all %}
<li>{{ myitem.item_name }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>

Django - Looping over unique model field in template

I have a model which a choice field, category, which the user must enter when submitting an entry. I would like to create a view in which each category has its own heading (only once), therefore each unique category would have its own heading, and then display the title associated to each category.
models.py
class Position(models.Model):
club_functions = Choices('Corporate Relations', 'Events & Conference', 'Marketing & Operations', 'Software Development', 'Product')
title = models.CharField(max_length=50)
category = models.CharField(choices=club_functions, max_length=30, blank=False)
description = models.TextField(blank=True)
spec_q1 = models.CharField(max_length=500)
spec_q2 = models.CharField(max_length=500)
views.py
def position_list_view(request):
all_objects = Position.objects.all()
context = {
'object_list' : all_objects
}
return render(request, "exec_list.html", context)
exec_list.html
{% for object.category in object_list %}
<h3>{{ object.category }}</h3>
<p>{{ object.title }}</p>
{% endfor %}
Any ideas on how to do this?
you can use regroup
{% regroup object_list by category as category_list %}
<ul>
{% for category in category_list %}
<li>{{ category.grouper }}
<ul>
{% for position in category.list %}
<li>{{ position.title }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>

How to add html inside {{ }} in django template

I want to know how to add html inside {{ }}:
{{ article.tags.all|join:", " }}
This return tags separated by coma for example: sports, cricket, nature etc
I want to do this:
{{ <span class="label">article.tags.all|join:", "</span> }}
I want to design each tag with adding a span class and remove coma
Models.py:
class Tag(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, null=True, default='')
class article(models.Model):
title = models.CharField(max_length=250)
disc = models.TextField(verbose_name="Discription")
posted = models.DateTimeField(auto_now_add=True, editable=False)
updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
Try with this:
{% for tag in article.tags.all %}
<span class="label">{{ tag }}</span>{% if not forloop.last %}, {% endif %}
{% endfor %}
After following the discussion:
{% for tag in article.tags.all %}
{% if tag.title == 'hello' %}
Special tag: <span>{{ tag }}</span>
{% else %}
<span>{{ tag }}</span>
{% endif %}
{% endfor %}

Iterate Items in Their Specific Groups in Django

In my Django template I want to be able to iterate through groups and items, but I want to iterate the items underneath their group. So far I have them iterating like this but it does not show which groups the items are a part of. How would I iterate the template to get this inclusion?
Views:
def manage(request):
group_list = Group.objects.order_by('name').filter(user=request.user)
item_list = Item.objects.order_by('name').filter(user=request.user)
return render(request, 'manage.html', {'group_list': group_list, 'item_list': item_list})
Template:
{% extends "base.html" %}
{% block content %}
{% for group in group_list %}
{{ group.name }}<br />
{% endfor %}
{% for item in item_list %}
{{ item.name }}<br />
{% endfor %}
{% endblock %}
UPDATE
Models (Sorry forgot to include this):
class Group(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=30)
class Item(models.Model):
user = models.ForeignKey(User)
group = models.ManyToManyField(Group)
name = models.CharField(max_length=30)
Your approach does unneccessary additional database hits. For performance reasons you should select just the items with related groups like this:
def manage(request):
item_list = Item.objects.order_by(
'group__name', 'name').filter(
user=request.user).select_related('group')
return render(request, 'manage.html', {'item_list': item_list})
The template looks like this:
{% extends "base.html" %}
{% block content %}
{% for item in item_list %}
{% ifchanged item.group.name %}
{{ item.group.name }}<br />
{% endifchanged %}
{{ item.name }}<br />
{% endfor %}
{% endblock %}
That way you only have ONE database hit regardless of how many groups there are.
I guess you have a fk from item to group
class Item(models.Model):
group = models.ForeignKey(Group)
views:
def manage(request):
group_list = Group.objects.order_by('name').filter(user=request.user)
return render(request, 'manage.html', {'group_list': group_list})
template:
{% extends "base.html" %}
{% block content %}
{% for group in group_list %}
{{ group.name }}<br />
<p>Item for this group</p>
{% for item in group.item_set.all %}
{{item.name}}
{% endfor %}
{% endfor %}
{% endblock %}

How to display objects grouped by foreign key

I'm a django n00b and am lost on how to do this.
sample models:
class Food_Type(models.Model):
name = models.CharField(max_length=200)
class Food(models.Model):
name = models.CharField(max_length=200)
food_type = models.ForeignKey(Food_Type)
And some data:
v = Food_Type(name='Veggie')
f = Food_Type(name='Fruit')
c = Food(food_type=v, name='carrot')
a = Food(food_type=f, name='apple')
The HTML output should look something like this:
Veggie
carrot
Fruit
apple
I'm uncertain of the right way to do the grouping, I assume the view and not the template.
food_type_list = Food_Type.objects.all().order_by('name')
food_list = []
for ft in food_type_list:
food_list.append(Food.objects.filter(fruit_type__exact=device_type.id)
render_to_response(some_template,
{'food_type': food_type_list, 'foods': food_list}
)
based on my view, I'm uncertain how to display
Does not work and there has got to be a better way
{% for type in food_type %}
{{ type }}
{% for food in foods %}
{% if food.food_type == type %}
{{ food.name }}
{% endif %}
{% endfor %}
{% endfor %}
I think you are looking for regroup
food = Food.objects.all()
{% regroup food by food_type as food_list %}
<ul>
{% for food_type in food_list %}
<li>{{ food_type.grouper }}
<ul>
{% for item in food_type.list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Simple:
Food.objects.order_by('food_type__name')

Categories

Resources