我知道Django有get_previous_by_FOO和get_next_by_FOO方法,但我不知道如何在我的模板和视图中使用它们。所以,请帮我把这两种方法用于我的项目。
我正在运行Django1.7
和Python2.7
,我的应用名称为blog
这是我的相应文件:
博客/ views.py
def view_post(request, slug):
post = get_object_or_404(Post, slug=slug)
return render_to_response('blog/blog_post.html',
{
'post':post,
},
context_instance=RequestContext(request))
class PublishedPostMixin(object):
def get_queryset(self):
return self.model.objects.live()
class PostDetailView(PublishedPostMixin,DetailView):
model = Post
博客/ models.py
class Post(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255,unique=True)
content = MarkdownField()
published = models.BooleanField(default=True)
author = models.ForeignKey(User, related_name="posts")
tags = models.ManyToManyField(Tag)
class Meta:
ordering = ["-created_at", "title"]
def __unicode__(self):
return self.title
def save(self, *args, ** kwargs):
if not self.slug:
self.slug = slugify(self.title) #title become the slug
super(Post, self).save(*args,**kwargs)
@models.permalink
def get_absolute_url(self):
return ("blog:detail",(),{'slug':self.slug
})
博客/ urls.py
urlpatterns = patterns('',
url(r"^(?P<slug>[\w-]+)/$",view_post, name="detail"),
)
<p>
{{ post.content|markdown }}
</p>
<ul class="pager">
<li class="previous">
<a href="{{post.get_previous_by_created_at}}">← Previous Posts</a>
</li>
<li class="next">
<a href="{{post.get_next_by_created_at}}">Next Posts →</a>
</li>
</ul>
答案 0 :(得分:1)
最后,我通过在模板中引入url标记解决了这个问题。这是我修改过的模板。
{% load url from future %}
<ul class="pager">
{% if post.get_next_by_created_at %}
<li class="previous">
<a href="{% url 'blog:detail' post.get_next_by_created_at.slug %}">← Previous Post</a>
</li>
{% endif %}
{% if post.get_previous_by_created_at %}
<li class="next">
<a href="{% url 'blog:detail' post.get_previous_by_created_at.slug %}">Next Post →</a>
</li>
{% endif %}
</ul>