python - 在 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>
解决方案
您需要获取get_absolute_url
下一个实例的。the_next
只是一个Picture
,而不是它的链接,所以:
<a href="{{ the_next.get_absolute_url }}">Next</a>
推荐阅读
- maven - Maven 多模块层次结构
- css - 您可以在不导入所有内容的情况下从另一个文件中引用 SASS 函数吗?
- java - DynamoDB 分页 - 最后一页上的最后评估键不为空
- ajax - Laravel cookie - 不使用 ajax 请求删除
- scala - Scala:进行柯里化时的函数声明
- javascript - 用browserify编译反应,babel说:ReferenceError:React未定义
- android - Snackbar 持续时间在某些设备上无法正常工作
- c++ - 构建用于函数的类型列表
- c - 我怎样才能找到任何字符的立即重复?
- django - Django Rest Framework:无法从给定的令牌中获取用户 ID