为此,您将需要两个 url 模式,它们将映射到两个视图。第一个 url 用于主页 ( http://localhost:8000/
),第二个 url 用于查看特定漫画 ( http://localhost:8000/<comic_id>
)。然而,第一个 url 应该将用户重定向到最新的漫画,使用HttpResponseRedirect
.
# assuming comic model similar to
class Comic(models.Model):
created = models.DateTimeField(auto_now_add=True)
# other fields...
# urlpatterns
url(r'^$', 'index', name='index'),
url(r'^(?P<comic_id>\d+)/$', 'comic', name='comic'),
# views
def index(request):
latest_comic = Comic.objects.order_by('-created')[0]
# or as suggested by Alasdair's comment
# latest_comic = Comic.objects.latest('created')
return HttpResponseRedirect(reverse('comic', kwargs={'comic_id':latest_comic.pk}))
def comic(request, comic_id):
comic = get_object_or_404(Comic, pk=comic_id)
# ...