Django / Django Views and URL Routing

Creating Function-Based Views in Django

This tutorial is about creating Function-Based Views (FBVs) in Django. You will learn how to use simple functions to respond to HTTP requests in your web application.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explains how to create views and configure URL routing in Django applications.

Creating Function-Based Views in Django Tutorial

1. Introduction

1.1 Tutorial Goal

This tutorial aims to guide you through creating Function-Based Views (FBVs) in Django, a popular Python web framework. FBVs in Django are simple functions that take a web request and return a web response.

1.2 Learning Outcomes

By the end of this tutorial, you should be able to:
- Understand what Django Function-Based Views are
- Create basic Function-Based Views
- Use Function-Based Views to handle HTTP requests

1.3 Prerequisites

You should have basic understanding of Python and familiarity with Django framework. Also, you need to have Django installed on your system.

2. Step-by-Step Guide

2.1 Understanding Django Function-Based Views

In Django, views define what data is displayed and how it's presented. They act as a connection between your models and templates. A Function-Based View is a Python function that takes a Web request and returns a Web response.

2.2 Creating a Basic Function-Based View

Here's how you can create a simple FBV in Django:

from django.http import HttpResponse

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

This function, hello_world, takes a request object and returns a HttpResponse object. The HttpResponse takes a string parameter representing the content of the page.

2.3 Best Practices and Tips

  • Keep your views skinny. Views should only fetch and pass data to templates or forms. Avoid placing business logic inside views.
  • Use Django's generic views where possible. They offer built-in functionality that saves time and effort.

3. Code Examples

3.1 Basic Function-Based View Example

Below is a simple Function-Based View which returns a plain HttpResponse.

from django.http import HttpResponse

def hello_world(request):
    # This view function takes a web request and returns a HttpResponse
    return HttpResponse("Hello, World!")

When you navigate to the URL linked to this view, you will see "Hello, World!" displayed on the page.

3.2 Function-Based View with Template Example

This example shows how to render a template with a context variable.

from django.shortcuts import render

def greet_name(request, name):
    # This view function takes a request and a name parameter, 
    # then renders a template with a context variable
    return render(request, 'greet.html', {'name': name})

In this example, 'greet.html' is the template, and we're passing a context variable named 'name'. The template can then use this context variable.

4. Summary

In this tutorial, we have covered the basics of creating Function-Based Views in Django. You learned what FBVs are, how to create them, and how to use them to handle HTTP requests. The next step would be learning about Django's Class-Based Views and how they differ from FBVs.

5. Practice Exercises

5.1 Exercise 1

Create a Function-Based View that takes a number as a parameter and returns a HttpResponse with that number squared.

5.2 Exercise 2

Create a Function-Based View that renders a template. Pass a list of your favorite books as a context variable to the template.

5.3 Exercise 3

Create a Function-Based View that accepts a form post, then displays the submitted data.

These exercises will help you practice your understanding of Function-Based Views in Django. Try to solve them on your own, then check the solutions below.

Solutions

# Solution for Exercise 1
def square_number(request, number):
    return HttpResponse(number ** 2)

# Solution for Exercise 2
def favorite_books(request):
    books = ["Book1", "Book2", "Book3"]
    return render(request, 'books.html', {"books": books})

# Solution for Exercise 3
from django.views.decorators.http import require_POST

@require_POST
def display_form_data(request):
    form_data = request.POST
    return render(request, 'form_data.html', {"data": form_data})

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help