Passing Data to the Front End

So we have the list of posts in the back end and we're even printing it out. Dope. Now we need to pass that info on to the front-end so we can make an HTML file with our post information that we just got from the database.

We do this by creating a dictionary and passing that in as a third argument to our render function:

class HomePage(View):
    def get(self, request):
        context = {}
        # code to query the database goes here!
        posts = Post.objects.all()
        # add data to context
        context["posts"] = posts
        return render(request, 'index.html', context)

Now, render is 'rendering' the index.html file with the context. We'll specify exactly what it does in the next section.


The last thing is that we want to display the posts in order of most recently posted first. However, they are in our posts list in order of oldest first (based on when they were saved to the database). Thus, we just have to reverse our list as follows and we should be good:

class HomePage(View):
    def get(self, request):

        context = {}
        # code to query the database goes here!
        posts = Post.objects.all()[::-1]
        # add data to context
        context["posts"] = posts
        return render(request, 'index.html', context)

results matching ""

    No results matching ""