← Django tutorial

Django

Views

A view is a Python function (or class) that receives an incoming request and returns a response.

Example: a view listing posts, newest first

# blog/views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all().order_by('-published_at')
    return render(request, 'blog/post_list.html', {'posts': posts})
Renders the blog/post_list.html template with every Post, newest
first, available as {{ posts }}.

Post.objects.all().order_by('-published_at') is Django's ORM, the same kind of query you saw in the SQL tutorial's ORDER BY lesson, expressed as Python method calls instead of a raw SQL string. The leading - before published_at means descending order, exactly matching SQL's ORDER BY published_at DESC. render() is the bridge between a view's Python data and the actual HTML template that displays it, covered properly two lessons from now.

Example
# blog/views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all().order_by('-published_at')
    return render(request, 'blog/post_list.html', {'posts': posts})
Output
Renders the blog/post_list.html template with every Post, newest first, available as {{ posts }}.
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Backend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account