我有一个用于获取最新条目的模板标签,但我似乎无法访问“get_absolute_url”函数。
我的错误是
No module named app2 (not the name of the app I'm trying to use)
我的新闻模特是这样的:
STATUS_CHOICES = (
(DRAFT, _('Draft')),
(HIDDEN, _('Hidden')),
(PUBLISHED, _('Published'))
)
TYPE_CHOICES = (
('normal', _('Normal')),
('special', _('Special')),
)
class Entry(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
body = RichTextField(null=True, blank=True)
start_publication = models.DateTimeField(blank=True, null=True)
end_publication = models.DateTimeField(blank=True, null=True)
status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT)
arttype = models.CharField(max_length=10, choices=TYPE_CHOICES, default='normal', )
objects = models.Manager()
published = EntryPublishedManager()
def __unicode__(self):
return self.title
class Meta:
ordering = ['-start_publication']
get_latest_by = 'creation_date'
@models.permalink
def get_absolute_url(self):
creation_date = timezone.localtime(self.start_publication)
return ('entry_detail', (), {
'year': creation_date.strftime('%Y'),
'month': creation_date.strftime('%b').lower(),
'day': creation_date.strftime('%d'),
'slug': self.slug})
我的urls.py是这样的:
urlpatterns = patterns('',
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', DateDetailView.as_view(allow_future=True, date_field='start_publication', queryset=Entry.objects.all()), name='entry_detail'),
)
我的templatetag latest_news.py:
from django import template
from apps.news.models import Entry
register = template.Library()
def show_news():
entry = Entry.published.filter(arttype='normal').order_by('-start_publication')[:4]
return entry
register.assignment_tag(show_news, name='latest_news')
我的frontpage.html模板:
{% latest_news as latest_news %}
{% for entry in latest_news %}
<h2>{{ entry.title }}</h2>
<p><a href="{{ entry.get_absolute_url }}">Read more</a></p>
{% endfor %}
{{entry.title}}工作正常。但不是.get_absolute_url。为什么要尝试导入另一个应用程序?
答案 0 :(得分:1)
在get_absolute_url
中,您忘记在网址上拨打reverse
。你正在传递元组,这使它无效。您的get_absolute_url
应为:
from django.core.urlresolvers import reverse
def get_absolute_url(self):
creation_date = timezone.localtime(self.start_publication)
return reverse('entry_detail', kwargs={
'year': creation_date.strftime('%Y'),
'month': creation_date.strftime('%b').lower(),
'day': creation_date.strftime('%d'),
'slug': self.slug})
permalink
decorator is deprecated and the use of reverse
is recommended
答案 1 :(得分:0)
您在项目中的其他位置,在urls.py中引用的应用中发生错误。
反向URL查找功能(您使用@permalink
装饰器隐式使用)必须导入urls.py文件中引用的所有视图,以便计算正确的值。如果某处出现错误,则会失败。
您应该找到app2
的引用,无论它在哪里,并修复它。