多対多の関係、レシピ、タグに関連する2つのアプリがありますが、image!= nullとRecipesのタグのクエリを取得する際に問題があります現在公開中です。多対多関係でImageFieldを取得する
レシピアプリ:レシピ/ models.py
from django.db import models
from django.contrib.auth.models import User
from tags.models import Tag
DRAFT = 'D'
PUBLISHED = 'P'
RECIPE_STATES = (
(DRAFT, 'Draft'),
(PUBLISHED, 'Published')
)
class Recipe(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100, unique=True)
date_created = models.DateField(auto_now_add=True)
date_modified = models.DateField(auto_now=True)
state = models.CharField(max_length=1, choices=RECIPE_STATES)
ingredients = models.TextField(blank=True)
introduction = models.TextField(blank=True)
preparation = models.TextField(blank=True)
tip = models.TextField(blank=True)
rating = models.IntegerField(blank=True)
diners = models.IntegerField(blank=True)
tags = models.ManyToManyField(Tag, blank=True)
def __str__(self):
return self.title
とタグアプリ:タグ/ models.py
from django.db import models
class Tag(models.Model):
name = models.CharField(max_length=50, unique=True)
image = models.ImageField(blank=True, null=True, upload_to='categories')
def __str__(self):
return self.name
レシピ/ views.py:
class HomeView(View):
def get(self, request):
queryset = Recipe.objects.filter(state=PUBLISHED)
last_recipes = queryset.order_by('-date_created')
top_recipes = queryset.order_by('-rating')
categories = Tag.objects.filter(image__isnull=False, recipe__state=PUBLISHED)
context = {
'last_recipes': last_recipes[:4],
'top_recipes': top_recipes[:4],
'categories': categories
}
return render(request, 'recipes/home.html', context)
私はhome.htmlのviews.pyからそのクエリを取得しようとしています:
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
{% for category in categories %}
<a href="{% url 'category_recipes' category.name %}">
<div class="col-xs-6 col-sm-4 col-md-3 text-center">
<h3>{{ category.name }}</h3>
<img src="{{ category.image.url }}" alt="{{ category.name }}" height="100">
</div>
</a>
{% endfor %}
</div>
</div>
私はこのエラーを取得しています:
ValueError at/
The 'image' attribute has no file associated with it.
ありがとう、私はついにそれを働かせます! – javiergarval