Search code examples
pythondjangodjango-modelsdjango-viewsdjango-urls

Using get_next_by_FOO and get_previous_by_FOO in django


I am building off of the question listed here: How can I use get_next_by_FOO() in django?

I have altered the code for my project (see below), but when I click on "next" to hyperlink to the next object in my Picture model the same page only reloads. Can someone tell me what I am doing wrong?

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>

Solution

  • You need to obtain the get_absolute_url of the next instance. the_next is only a Picture, not its link, so:

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