我正在学习 Django,目前我正在一个项目中松散地遵循民意调查教程。
现在我正在尝试转换为通用视图,这就是我遇到问题的地方:
新闻/models.py
[...]
class News(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
category = models.CharField(max_length=50L)
title = models.CharField(max_length=200L)
#rss_summary = models.CharField(max_length=2000L)
rss_summary = models.TextField(max_length=2000L)
#body_text = models.CharField(max_length=5000L)
body_text = models.TextField(max_length=5000L)
post_date = models.DateTimeField()
class Meta:
db_table = 'news'
def __unicode__(self):
return self.title
新闻/urls.py
from django.conf.urls import patterns, url, include
from django.views.generic import DetailView, ListView
from news import views
from news.models import News
urlpatterns = patterns('',
url(r'^$',
ListView.as_view(
queryset=News.objects.order_by('-post_date'),
context_object_name='allnews',
template_name='news/news.html'),
name='news_index'),
[...]
新闻/模板/新闻/news.html
[...]
{% for item in allnews %}
<h1 class="news"><a href="{% url 'news_index' item.id %}">{{item.title}}</a></h1>
[...]
{% endfor %}
现在我的问题是:我想使用ListView或DetailView{% url 'foo' id %}
等通用视图的语法链接到特定的新闻项目(通过 ID) 。我怎样才能做到这一点?我为 ListView 声明了一个名称,但我无法弄清楚如何指定.allnews.id
使用上面的代码,我得到了错误
NoReverseMatch at /news/ 未找到带有参数“(7L,)”和关键字参数“{}”的“news_index”的反向。
有趣的是,“7L”是最新消息的id……