在多对多关系中检索ImageField

时间:2017-06-23 16:44:27

标签: django

我有两个与多对多关系,食谱和标签相关的应用程序,而且我在检索带有image!= null的标签和当前已发布的食谱的查询时遇到了麻烦。

食谱app:recipes / 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

标签应用:tags / 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.

我还有填充数据的标签: Tags API

2 个答案:

答案 0 :(得分:0)

检查,ID = 20的标签没有&#39;&#39; (空字符串)作为值。您只排除空值,但不检查空字符串。

答案 1 :(得分:0)

我终于使用它了:

categories = Tag.objects.filter(image__isnull=False, recipe__state=PUBLISHED).distinct()

现在,home.html中的类别提供了数据,我在使用category.image.url时遇到了麻烦。