【发布时间】: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