Шаблон Django html не отображает данные Queryobject
У меня проблема с тем, что html-шаблон не отображает поля модели, отправленные из представления, в контекстном словаре под названием content.
В model.py:
class Ingredients(models.Model):
id = models.IntegerField(primary_key=True)
recipe = models.ForeignKey(Recipes, on_delete=models.CASCADE, related_name='ingredients')
ingredient = models.CharField(max_length=128)
class Meta:
managed = False
db_table = 'ingredients'
verbose_name_plural = 'Ingredients'
def __str__(self):
return f"{self.id} {self.recipe} - {self.ingredient}"
class Recipes(models.Model):
id = models.IntegerField(primary_key=True)
category = models.TextField(db_column='Category', null=False)
submitted_by = models.TextField(
db_column='Submitted_By', null=False)
origin = models.TextField(db_column='Origin', null=False)
title = models.TextField(db_column='Title', null=False)
directions = models.TextField(
db_column='Directions', null=False)
comments = models.TextField(db_column='Comments', null=False)
created = models.DateTimeField(null=False)
modified = models.DateTimeField(null=True)
def __str__(self):
return f"{self.id} - {self.title}"
class Meta:
managed = False
db_table = 'recipes'
verbose_name_plural = 'Recipes'
В views.py:
recipes = Recipes.objects.all().order_by(
"category", "title")
content['ingredients'] = {}
for recipe in recipes:
ingredients = Ingredients.objects.filter(
recipe=recipe.id).order_by("id")
content['ingredients'][recipe.id] = ingredients
content['recipes'] = recipes
В файле recipes.html:
{% for recipe in recipes %}
<div id="id-{{recipe.id}}" class="grid-item {{recipe.category}} {{recipe.submitted_by}}">
<div class="row">
<div class="col-12 col-md-3 ingredients">
{% for queryQbject in ingredients.recipe.id %}
{{ queryQbject.ingredient }}<br>
{% empty %}
<span>No ingredients provided</span>
{% endfor %}
</div>
</div>
{% endfor %}
Я получаю правильные данные из базы данных sqlite, и Queryset хранится в словаре 'content', который правильно передается в html-файл. Однако html-шаблон не отображает никаких данных и только печатает сообщение "No ingredients provided" {% empty %} case.
Смотрите отладочную информацию:
Что мне нужно сделать, чтобы решить эту проблему?
Вы пытаетесь выполнить цикл по идентификатору, который является целым числом. Это не итерабельность. Изменить
{% for queryQbject in ingredients.recipe.id %}
To
{% for queryQbject in ingredients.recipe %}
Ответ Нигеля239 заставил меня задуматься и поискать еще немного. Я нашел этот пост https://fedingo.com/how-to-lookup-dictionary-value-with-key-in-django-template/ написать пользовательский фильтр для поиска значения словаря с ключом.
Это мой custom_tags.py:
@register.filter
def get_item(dictionary, key):
try:
key = int(key)
value = dictionary.get(key)
except:
value = None
return value
и мой обновленный файл recipes.html:
<div class="col-12 col-md-3 ingredients">
{% for queryset in ingredients|get_item:recipe.id %}
{{ queryset.ingredient }}<br>
{% empty %}
<span>No ingredients provided</span>
{% endfor %}
</div>
Теперь код правильно извлекает все ингредиенты из Django Queryset, который был передан в html-шаблон, в словарь под названием 'ingredients', используя 'recipe.id' в качестве ключей.