【问题标题】:Using get_next_by_FOO and get_previous_by_FOO in django在 django 中使用 get_next_by_FOO 和 get_previous_by_FOO
【发布时间】:2021-05-17 08:01:43
【问题描述】:

我正在构建这里列出的问题:How can I use get_next_by_FOO() in django?

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

Models.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 })

views.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)

urls.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>

【问题讨论】:

    标签: python django django-models django-views django-urls


    【解决方案1】:

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

    &lt;a href="{{ the_next<b>.get_absolute_url</b> }}"&gt;Next&lt;/a&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 2020-07-26
      • 2021-10-07
      • 2014-04-11
      • 2011-09-08
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多