【问题标题】:Django Category Model and Template View IssueDjango 类别模型和模板视图问题
【发布时间】:2016-04-27 02:53:14
【问题描述】:

我的问题是两个阶段的,但它来自同一个 Django 模型。我正在尝试让我的 Category 模型与我的 Petition 模型一起正常工作。目前,

当我为“CategoryView”类定义查询集时出现此“FieldError”错误:

Cannot resolve keyword 'created_on' into field. Choices are: description, id, petition, slug, title

这是“CategoryView”类的代码:

class CategoryView(generic.ListView):
    model = Category
    template_name = 'petition/category.html'
    context_object_name = 'category_list'

    def get_queryset(self):
        return Category.objects.order_by('-created_on')[:10]

这是我的 models.py 中的代码:

class Category(models.Model):
    title = models.CharField(max_length=90, default="Select an appropriate category")
    slug = models.SlugField(max_length=200, unique=True)
    description = models.TextField(null=False, blank=False)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return "/categories/%s/"%self.slug

class Petition(models.Model):
    title = models.CharField(max_length= 90, default="Enter petition title here")
    created_on = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(null=False, upload_to=imageupload)
    video = models.CharField(max_length=600, default="Enter an external video link")
    petition = models.TextField(null=False, default="Type your petition here")
    created_by = models.ForeignKey(User)
    category = models.ManyToManyField(Category)

    def total_likes(self):
        return self.like_set.count()

    def __str__(self):
        return self.title[:50]

    def get_signatures(self):
        return self.signature_set.all()

当定义了“get_queryset()”时,我的类别视图模板 (category.html) 上出现了“FieldError”。

当我将其注释掉时,页面显示但未检索到帖子;我得到了一个类别列表。这是我的类别视图模板(category.html):

{% include 'layout/header.html' %}
{% load humanize %}

    <div class="container content">
    <div class="row">
    <div class="col-md-8 post-area">
    {% if category_list %}
{% for petition in category_list %}
<div class="petition-block">
<h2 class="home-title"><a href="{% url 'detail' pk=petition.id %}">{{petition.title}}</a></h2>
<span class="petition-meta">
Created {{petition.created_on|naturaltime}} by 
{% if petition.created_by == user %}
You 
{% else %}
@{{ petition.created_by }}
{% endif %} 
    {% if petition.created_by == user %}
    <a href="{% url 'editpetition' pk=petition.id %}">Edit</a>
    {% endif %}
    {% if petition.created_by == user %}
    <a href="{% url 'deletepetition' pk=petition.id %}">Delete</a>
    {% endif %}
</span>

    {% if petition.image %}
        <img src="{{ petition.image.url }}" alt="petition image" class="img-responsive" />
    {% endif %}

</div><!--//petition-block-->
{% endfor %}

{% else %}

    <p>Sorry, there are no posts in the database</p>

{% endif %}
</div>


<div class="col-md-4">
<h3>Topics</h3>
<ul>
    {% for petition in category_list %}
    <li><a href="#">{{petition.title}}</a></li>
    {% endfor %}
</ul>
</div>

</body>
</html>

我做错了什么?请帮忙。

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    这是因为您试图通过 created_on 对 Category 的查询集进行排序,而您的 Category 模型没有任何名为 created_on 的字段。该字段在请愿模型中。如果您想通过请愿书的 created_on 对类别进行排序,您应该在表之间进行“连接”,但是使用 Django 的 ORM 很容易。

    为了简化代码,最好命名关系

    class Petition(models.Model):
        ...
        categories = models.ManyToManyField(Category, related_name='petitions')
        ...
    

    现在您可以将类别的请愿书称为“请愿书”

    Category.objects.order_by('-petitions__created_on')
    

    要在模板中使用请愿书,最好的方法是在查询集上预取请愿书,以避免在 for 循环中每次都访问数据库。

    Category.objects.prefetch_related('petitions').order_by('-petitions__created_on')
    

    这将带来每个类别的每个请愿书。所以在你的模板中你可以使用:

    {% for category in category_list %}
        {% for petition in category.petitions.all %}
            ...
            @{{ petition.created_by }}
            ...
        {% end for %}
    {% end for %}
    

    【讨论】:

    • 感谢您的回复。我的查询集中返回的值与您的建议相同,但我仍然收到相同的错误:Cannot resolve keyword 'petition_set__created_on' into field.
    • 好的,我将其更改为:def get_queryset(self): return Category.objects.order_by('-petition__created_on')[:10],现在加载正常,只是模板 (category.html) 仍在返回类别列表,而不是在类别中显示帖子
    • 啊,那是因为您只是将类别传递给模板。看看列表视图是如何工作的ccbv.co.uk/projects/Django/1.9/django.views.generic.list/…。我将编辑答案以完成您的问题
    • 我遇到另一个错误:Cannot find 'petition' on Category object, 'petition' is an invalid parameter to prefetch_related()
    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 2015-06-02
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    相关资源
    最近更新 更多