我有新闻和新闻的类别,我不知道如何使用属于同一类别的新闻列表呈现页面。希望你能帮助我。 这是我的model.py文件:
from django.db import models
class Category(models.Model):
class Meta:
verbose_name_plural = u'Categories'
category = models.CharField(max_length=255)
slug = models.CharField(max_length=255)
def __unicode__(self):
return self.category
class News(models.Model):
class Meta:
verbose_name_plural = u'News'
title = models.CharField(max_length=255)
category = models.ForeignKey(u'Category', related_name=u'Category', blank=True, null=True)
pub_date = models.DateTimeField('date published')
slug = models.CharField(max_length=255)
short_content=models.TextField(max_length=2000, blank=True)
content = models.TextField(max_length=10000)
image = models.FileField(u'Images', upload_to='media/img/news', blank=True)
def __unicode__(self):
return self.title
views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from news.models import News
class NewsListView(ListView):
template_name ='news/list.html'
context_object_name = 'news_list'
def get_queryset(self):
return News.objects.order_by('-pub_date') [:5]
class NewsDetailView(DetailView):
model=News
template_name = 'news/detail.html'
def CategoryNews(request, categoryslug):
category = Category.objects.get(slug=categoryslug)
news = News.objects.filter(category=category)
return render (request, 'news/category_news.html', {'category' : category})
urls.py:
django.conf.urls import patterns, url
from news.views import NewsListView, NewsDetailView
from news import views
urlpatterns = patterns('',
url(r'^$', NewsListView.as_view(), name='list'),
url(r'^(?P<slug>[-_\w]+)/$', NewsDetailView.as_view()),
url(r'^kids-garden/$', views.CategoryNews),
)
谢谢!
答案 0 :(得分:0)
我认为这应该可以胜任:
views.py
....
from news.models import News, Category
def CategoryNews(request, categoryslug):
category_news = News.objects.filter(category__slug='categoryslug')
return render (request, 'news/category_news.html', {'category_news' : category_news})
答案 1 :(得分:0)
在CategoryNews视图中添加新闻以呈现上下文。这将使新闻项目在模板中可用。
def CategoryNews(request, categoryslug):
category = Category.objects.get(slug=categoryslug)
news = News.objects.filter(category=category)
return render (request, 'news/category_news.html', {'category' : category, 'newsitems': news})
将命名组添加到类别网址以使其动态化。
重写
url(r'^kids-garden/$', views.CategoryNews, name='category'),
到
url(r'^category/(?P<categoryslug>\w+)/$', views.CategoryNews, name='category'),
在category_news.html
中{%for news in newsitems%}
{{ news.title }}
{{ news.content }}
# rest values...........
{% endfor %}