Views

What do Views Handle?

Views in Django handle the core logic of your app. They are responsible for processing incoming HTTP requests, interacting with the database (if required), and returning an appropriate HTTP response such as a rendered HTML template, redirect, or plain text.

This includes:

  • Returning plain text or HTML
  • Rendering templates with context
  • Redirecting users
  • Processing form data
  • Querying or modify data in from a database
  • Displaying feedback messages

Imports

At the top of your views file, you should import any required methods such as:

Purpose Import What is does
Return plain text or HTML from django.http import HttpResponse Sends a custom plain text or HTML response directly to the browser.
Render templates from django.shortcuts import render Loads an HTML template and returns it with an optional context dictionary.
Redirect users from django.shortcuts import redirect Redirects the user to another URL, either a named URL pattern or path.
Process form data from .forms import YourFormName Imports a form class from the forms.py file in the same app.
Redirect after POST from django.http import HttpResponseRedirect Used to redirect after successful form submission.
Query the database from .models import YourModelName Imports a model from the same app so you can retrieve or save data.
Use messages framework from django.contrib import messages Enables feedback messages after actions.

Functions

Template Rendering

To direct users to pages, you can define functions that are typically named after the page or template you wish to render that takes request as an argument.

Inside this function, you return a call to render(), passing in:

  • The request object
  • The relative path to the template (e.g., 'appname/page_name.html')

For example, in a to do app:

# todo/views.py
from django.shortcuts import render
def todo_list(request):
    return render(request, 'todo/todo_list.html')
  • This view will render the file located at todo/templates/todo/todo_list.html.
  • The file path is relative to the templates search path, not the full system path.

Troubleshooting

If this is not working for you, check your settings.py file for APP_DIRS = True in your TEMPLATES setting. This is what allows Django to automatically search for templates inside each app's templates/ folder.

Returning Context to Templates

To return context in your template rendering functions, create a context dictionary of variables and then pass this context dictionary as a third parameter in the render() function behind the request object and the template path. Generally, the keys defined within the context dictionary will have the same name as the values defined within the function e.g. 'products': products, but for clarity; the key on the left hand side will be the variable that you can access in the template using the Django templating language e.g. and the value is the Python variable defined in the function.

# views.py
from django.shortcuts import render
from .models import Product

def product_list(request):
    # Get instances of the Product model
    products = Product.objects.all()

    # Define another variable you want to use
    sum_variable = 21 + 2

    # Define context
    # Here we will be able to access the instances of the product model
    # And the variable we defined above
    context = {
        'products': products,
	    'sum_variable': sum_vairable,
    }

    # Render with context
    return render(request, 'app_name/home.html', context)

Returning Plain Text

from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello, world!")

Redirecting Users

from django.shortcuts import redirect

def go_home(request):
    return redirect('home')  # where 'home' is a named URL in urls.py

After a Successful Form Submission

from django.http import HttpResponseRedirect

def submit_form(request):
    if request.method == 'POST':
        # process form data...
        return HttpResponseRedirect('/thanks/')