URL和基于django类的视图

时间:2013-01-14 22:32:58

标签: python django django-views django-urls

这是我在django(1.4)中使用基于类的视图完成的第一个项目,我在基于日期的归档中没有返回URL时遇到了一些麻烦。我已经在我的项目(公司内部网)中成功构建了几个不需要它们的应用程序,但该网站的“新闻”部分确实需要基于日期的存档。

年,月,日档案似乎都运行良好,但我的个别文章并没有产生我认为应该的URL。我很确定问题出在models.py中的get_absolute_url函数中,因为如果我输入URL我希望他们直接找到django并显示我想要的文章!

从我得到的shell调用get_absolute_url函数:

NoReverseMatch: Reverse for 'news_detail' with arguments '('2013', 'Jan', '14', 'another-news-thang')' and keyword arguments '{}' not found.

我已经阅读了relevant docs以及DateDetailView的具体参考资料,但在我出错的地方,我无法理解。

我的models.py是:

from django.db import models
import datetime
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from phone_list.models import Person, Team
from tinymce import models as tinymce_models
from taggit.managers import TaggableManager
from easy_thumbnails.fields import ThumbnailerImageField

class LiveNewsManager(models.Manager):
    def get_query_set(self):
        return super(LiveNewsManager, self).get_query_set().filter(status=self.model.LIVE_STATUS)

class News(models.Model):
    LIVE_STATUS=1
    DRAFT_STATUS=2
    HIDDEN_STATUS=3
    STATUS_CHOICES=(
        (LIVE_STATUS, 'Live'),
        (DRAFT_STATUS, 'Draft'),
        (HIDDEN_STATUS, 'Hidden'),
    )

    # core fields
    headline=models.CharField(max_length=250)
    image = ThumbnailerImageField(
        upload_to='news_images',
        resize_source=dict(size=(700, 500), sharpen=True),
        null=True,
        blank=True,
        help_text = "Optional. Photographs added here are given 'feature' status and should be landscape oriented.",
    )
    image_caption=models.CharField(
        max_length=144,
        blank=True,
        help_text = "DO NOT ADD IF THERE IS NO FEATURE IMAGE",
    )
    story = tinymce_models.HTMLField()
    pub_date=models.DateTimeField(default=datetime.datetime.now)

    # metadata
    writer=models.ForeignKey(Person)
    enable_comments=models.BooleanField(default=True)
    featured=models.BooleanField(default=False)
    slug=models.SlugField(unique_for_date='pub_date')
    status=models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)

    # categorization
    tags=TaggableManager()

    objects=models.Manager()
    live=LiveNewsManager()

    class Meta:
        verbose_name_plural='News articles'
        ordering=['-pub_date']

    def pictures(self):
        try:
            return [self.image]
        except:
            pass

    def get_absolute_url(self):
        return reverse ('news_detail', args = [str(self.pub_date.strftime("%Y")), str(self.pub_date.strftime("%b")), str(self.pub_date.strftime("%d")), str(self.slug)])

    def __unicode__(self):
        return self.headline

我的urls.py是:

from django.conf.urls import patterns, include, url
from haystack.forms import ModelSearchForm
from haystack.query import SearchQuerySet
from haystack.views import SearchView
from django.views.generic import ArchiveIndexView, YearArchiveView, MonthArchiveView, DayArchiveView, DateDetailView
from datetime import date
from news.models import News

sqs = SearchQuerySet().models(News)

urlpatterns = patterns('',
    url(r'^$', ArchiveIndexView.as_view(
        date_field = 'pub_date',
        model=News,
        context_object_name="latest_news",),
        ),
    url(r'^(?P<year>\d{4})/$', YearArchiveView.as_view(
        date_field = 'pub_date',
        model=News,
        context_object_name="year_archive",),
        ),
    url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$', MonthArchiveView.as_view(
        date_field = 'pub_date',
        model=News,
        context_object_name="month_archive",),
        ),
    url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', DayArchiveView.as_view(
        date_field = 'pub_date',
        model=News,
        context_object_name="day_archive",),
        ),
    url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', DateDetailView.as_view(
        date_field = 'pub_date',
        model=News,
        context_object_name="news_detail",),
        ),
    url(r'^search/$', SearchView(
        template='news/search.html',
        searchqueryset=sqs,
    ), name='haystack_search'),
)

对于稍微凌乱的代码感到抱歉;一旦我让它们工作,我倾向于清理它们。任何帮助非常感谢。

1 个答案:

答案 0 :(得分:3)

这里没有您的网址命名。

如果尚未在某处定义,则无法撤消news_detail

   url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',       
      DateDetailView.as_view(
        date_field = 'pub_date',
        model=News,
        context_object_name="news_detail",),
        ),
       name='news_detail'),  #<--- you're missing this