How can I make a page that will always display the latest post from my Django Model

Question:

Thank you to all of the people who looked at this in advance! I really appreciate it.

I have setup a very simple model that consists of two parameters (title, which is the date when this was published and the text, that’s it):

models.py

class Post(models.Model):
title = models.DateField(blank=True, null=True)
body = models.TextField()

def __str__(self):
    return str(self.title)

After following a standard “create a blog in Django tutorial” I have created two views that show the list of everything posted and a view that will show details of any selected post.

views.py

class NowListView(ListView):
model = Post
template_name = 'archive.html'

class NowDetailView(DetailView):
model = Post
template_name = 'then.html'

Finally, I have this urls.py that successfully shows all the posts at http://127.0.0.1:8000/now/archive and specific post at http://127.0.0.1:8000/now/archive/1 (or any other number, depending on the pk).

urls.py

urlpatterns = [
    path('archive', NowListView.as_view(), name='archive'),
    path('archive/<int:pk>', NowDetailView.as_view(), name='then'),
        ]

What I want to achieve is to display the latest post on http://127.0.0.1:8000/now.

I have tried a million ways to do it, and nothing worked, always something in the way (would take too long to write all of them). After all this tries it is obvious to me that I have to use a query to pull the latest post, but I have no working way of doing it.

I have tried using this Post.objects.earliest(‘title’) and this Post.objects.order_by(‘title’).first() in my urls as such:

urls.py

    urlpatterns = [
path('archive', NowListView.as_view(), name='archive'),
path('archive/<int:pk>', NowDetailView.as_view(), name='then'),    
path('>',NowDetailView.as_view(Post.objects.order_by('title').first()), name='then'),
        ]

This gives me an error:

TypeError: as_view() takes 1 positional argument but 2 were given

I have also tried creating a def function under my class in views.py, but the error then was that the urls couldn’t import it for some reason.

In any case, I am probably over thinking it and just simply being stupid. If anyone could help me with this I would be very grateful! Thanks a ton in advance and sorry for the long question!

Best,
Rasul Kireev

Asked By: Rasul Kireev

||

Answers:

This belongs in the view., not the URL.

You need to define get_object:

class NowLatestView(DetailView):
    model = Post
    template_name = 'then.html'

    def get_object(self)
        return Post.objects.order_by('title').first()
Answered By: Daniel Roseman

you can try this

model = Post.objects.order_by('-id')
Answered By: Carla
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.