我创建了一个简单的类别模型。
模型
我创建如下。我在哪里会在这些模型文件中出错?谢谢你的帮助。
models.py 我添加到文件中的代码如下。
class Category(models.Model):
category_name = models.CharField(max_length=250)
category_desc = models.TextField()
slug = models.SlugField(max_length=250, unique=True)
class Meta:
ordering = ('category_name',)
verbose_name = 'category'
verbose_name_plural = 'Categories'
def get_absolute_url(self):
return reverse('article:categories', args=[self.slug])
def __str__(self):
return self.category_name
views.py 我添加到文件中的代码如下。
def article_category(request, category_slug):
categories = Category.objects.all()
article = Article.objects.filter( article_status='published')
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
article = article.filter(category=category)
template = 'article/category.html'
context = {'article': article}
return render(request, template, context)
url.py
url(r'^category/(?P<category_slug>[-\w]+)/$', article_category, name='article_category'),
index.html 我添加到文件中的代码如下。
<a href="{{ articles.article_category.get_absolute_url }}">{{ article.article_category }}</a>
答案 0 :(得分:0)
You should remove the non-sens categories
variable in your view if you don't use it.
You can't call the .filter()
method on your instance.
Change:
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
article = article.filter(category=category)
to:
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
article = Article.objects.filter(article_status='published', category=category)
You have to provide a url slug, that condition is useless anyway.
The article
variable is a list with all of the entries that pass those filters. It must be articles
.
What index.html
has to do with your view, if you render the article/category.html
?
Why you render the article/category.html
, if you want to display all articles filtered by that category?
Why aren't you using ForeignKey
for this kind of relation.
If it's a list of articles, as I said, in your template you should have something like this (supposing you renamed article
with articles
):
{% for article in articles %}
<a href="{{ article.get_absolute_url }}">{{ article.name }}</a>
{% endfor %}
You haven't showed the Article model, so I supposed that there's .get_absolute_url
and .name
.
Ask me if you haven't understood something.