首页 > 解决方案 > 在 django 中使用 get_next_by_FOO 和 get_previous_by_FOO

问题描述

我正在建立这里列出的问题:如何在 django 中使用 get_next_by_FOO()?

我已经更改了我的项目的代码(见下文),但是当我单击“下一步”以超链接到我的图片模型中的下一个对象时,同一页面只会重新加载。有人可以告诉我我做错了什么吗?

模型.py

class Picture(models.Model):
    name = models.CharField(max_length=100)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='photo/')
    
    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('picture-detail', kwargs={ 'pk': self.pk })

视图.py

class PictureDetailView(DetailView):
    model = Picture

def picture_detail(request, id=None):
    instance = get_object_or_404(Picture, id=id)
    the_next = instance.get_next_by_date_posted()   
    context = {
        'name': instance.name,
        'instance': instance,
        'the_next': the_next,
    }
    return render(request, 'gallery/picture_detail.html', context)

网址.py

urlpatterns = [
path('', views.home, name='gallery-home'),
path('picture/', PictureListView.as_view(), name='gallery-picture'),
path('picture/<int:pk>/', PictureDetailView.as_view(), name='picture-detail'),
]

picture_detail.html

<a href="{{ the_next }}"> Next </a>

标签: pythondjangodjango-modelsdjango-viewsdjango-urls

解决方案


您需要获取get_absolute_url下一个实例的。the_next只是一个Picture,而不是它的链接,所以:

<a href="{{ the_next.get_absolute_url }}">Next</a>

推荐阅读