Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 12

Building a Basic View Function

Recommended resources

Hello! Welcome to your fourth lesson in the "Introduction to Django" module.

In our last lesson, we explored Django's architectural blueprint, the Model-Template-View (MTV) pattern. We established that the View is the logical core of the application, responsible for receiving a web request and orchestrating the creation of a web response.

Today, we will translate that theory into practice. The learning outcome is to create a simple view function that returns an HTTP response. This is your first step in writing active, functional code within the Django framework. We will create a basic view and then take a deeper look at the two fundamental objects it works with: the request it receives and the response it returns.

1. The Anatomy of a Django View

Before we write any code, let's establish a clear definition.

Writing views | Django documentation

The official Django documentation provides the most precise definition of a view. Please read the introductory paragraphs to formalize your understanding.

Read the section 'Writing views' up to, but not including, 'A simple view'. Focus on the core definition: a Python function that takes a web request and returns a web response.

As the documentation states, a view is simply a Python function (or, as we'll see later, a class) that adheres to two simple rules:

  1. It must accept an HttpRequest object as its first argument.
  2. It must return an HttpResponse object.

This is the fundamental contract of a Django view. The function's name doesn't matter, nor does the specific logic inside it. As long as it honors this input/output contract, Django can work with it.


2. Creating Your First View

Now, let's write the code. We will add a view function to the views.py file within our playground app that we created in a previous lesson.

The following video provides a clear, step-by-step demonstration.

Django Tutorial for Beginners – Build Powerful Backends

The 'Programming with Mosh' tutorial offers a practical walkthrough of creating your first view. We will follow his steps to create a simple 'say_hello' function.

Watch the segment from 00:25:27 to 00:27:24. Focus on the two key actions: importing HttpResponse and defining the say_hello function. Important: Stop watching at 00:27:24, as the video then moves on to URL mapping, which we will cover in the next lesson.

After following the video, your playground/views.py file should now contain the following code:

from django.http import HttpResponse

# Create your views here.
def say_hello(request):
    return HttpResponse('Hello World')

Congratulations! You have successfully created your first Django view. It's simple, but it perfectly fulfills the contract: it takes a request object and returns an HttpResponse containing the string 'Hello World'.

Right now, this function is just dormant Python code. There is no way for a user to trigger it. In our next lesson, we will connect this view to a URL, making it accessible via a browser. But first, let's dive deeper into the request and response objects to understand what's happening "under the hood," as you prefer.


3. The HttpRequest Object: Your Incoming Data

In the function def say_hello(request):, the request parameter is not just a variable name; it's a powerful object packed with information about the incoming request from the client. Django creates this HttpRequest object and passes it to your view automatically.

Think of it as a detailed report about the user's action. It answers questions like:

  • What URL path did they ask for?
  • What HTTP method did they use (GET, POST, etc.)?
  • What headers were included (e.g., User-Agent, Accept)?
  • If it was a POST request, what data did they submit?

Request and Response in Django

The article 'Request and Response in Django' provides a great overview of the HttpRequest object and some of its most useful attributes.

Read the section titled 'The HttpRequest object'. Pay attention to the list of attributes like request.method and request.headers. You don't need to memorize them, but appreciate that the request object is your window into the client's request.

For instance, your view could use request.method to perform different logic for GET and POST requests, or request.user to identify the logged-in user. This object is the primary way your backend logic gets context from the client.


4. The HttpResponse Object: Crafting Your Reply

Just as every view receives a request, it must return a response. The HttpResponse object is what you use to construct the reply that Django will send back to the client's browser.

The simplest response, as we've seen, contains a string of plain text. However, you have full control over the content and the metadata of the response, including the crucial HTTP status code.

Let's explore some possibilities.

Writing views | Django documentation

The Django documentation and the 'Djangotherightway' article together provide a comprehensive look at the capabilities of HttpResponse.

First, read the section 'A simple view' in the Django docs. This demonstrates how to return a response containing HTML. Then, read 'Returning errors' to see how you can return responses with specific error codes like 404 (Not Found).

Request and Response in Django

Now, let's supplement that with another resource that shows different types of responses.

Read the sections 'The HttpResponse object', 'JsonResponse object', and 'Returning 404 errors from HttpResponse'. This will show you how to build a response incrementally and, importantly for your goals, how to return a JSON response. The ability to return JsonResponse is fundamental to building the APIs you'll use to power AI applications.

From these readings, you can see that an HttpResponse is more than just a container for text. You can:

  • Pass it a string of fully-formed HTML.
  • Instantiate subclasses like HttpResponseNotFound to return a 404 status code with a custom message.
  • Set the status code directly, like HttpResponse(status=201) for "Created".
  • Use the JsonResponse subclass to easily serialize a Python dictionary into a JSON response, which is the standard for modern APIs.
Test your understanding!

Modify your say_hello view in playground/views.py. The new logic should inspect the request's method.

  • If the method is GET, the view should return an HttpResponse with the text "This was a GET request." and a standard 200 OK status.
  • For any other method (e.g., POST, PUT), it should return an HttpResponse with the text "Method Not Allowed." and a status code of 405.
Show answer

Your playground/views.py file should be updated to look like this:

from django.http import HttpResponse

def say_hello(request):
    if request.method == 'GET':
        return HttpResponse("This was a GET request.")
    else:
        # 405 is the status code for "Method Not Allowed"
        return HttpResponse("Method Not Allowed.", status=405)

This demonstrates using an attribute from the request object (request.method) to change the content and status of the HttpResponse object you return.


Conclusion

In this lesson, you wrote your first piece of Django logic. We defined the "contract" of a Django view and implemented it with a simple function. We then delved into the HttpRequest and HttpResponse objects, which are the fundamental building blocks of communication in any Django application.

Key Takeaways:

  • A Django view is a Python function that takes an HttpRequest object and returns an HttpResponse object.
  • Views are conventionally placed in an app's views.py file.
  • The HttpRequest object is a rich source of information about the client's request, including the HTTP method, headers, and path.
  • The HttpResponse object allows you to control the content (text, HTML, JSON) and status code of the reply sent back to the client.
  • Specialized subclasses like JsonResponse and HttpResponseNotFound simplify common response patterns.

Preview of the Next Lesson:
Our say_hello view exists, but it's unreachable. In the next lesson, "Configure URL routing in Django using urlpatterns to map URLs to views," we will bridge this gap. You will learn how to use Django's URL dispatcher to create a specific URL endpoint (e.g., /playground/hello/) that, when visited, will execute our view and display its response in the browser. This will complete our first full request-response cycle.