0
0
Djangoframework~5 mins

Function-based views basics in Django

Choose your learning style9 modes available
Introduction

Function-based views let you control what happens when someone visits a web page. They are simple Python functions that decide what to show or do.

You want to quickly create a simple web page that shows some text or data.
You need full control over the request and response process in your web app.
You want to handle form submissions or user input in a straightforward way.
You are learning Django and want to understand how views work before using more complex tools.
You want to write clear and easy-to-follow code for small or medium web pages.
Syntax
Django
from django.http import HttpResponse

def my_view(request):
    return HttpResponse('Hello, world!')

The function always takes request as the first argument.

It must return an HttpResponse or similar response object.

Examples
This view returns a simple text message for the homepage.
Django
from django.http import HttpResponse

def home(request):
    return HttpResponse('Welcome to the homepage!')
This view uses render to show an HTML template called about.html.
Django
from django.shortcuts import render

def about(request):
    return render(request, 'about.html')
This view takes an extra parameter name and greets the user personally.
Django
from django.http import HttpResponse

def greet(request, name):
    return HttpResponse(f'Hello, {name}!')
Sample Program

This is a complete function-based view that returns a plain text message when called.

Django
from django.http import HttpResponse

def simple_view(request):
    return HttpResponse('This is a function-based view example.')
OutputSuccess
Important Notes

Function-based views are easy to write and understand for beginners.

For more complex logic, Django also offers class-based views.

Always remember to connect your view to a URL in urls.py to make it accessible.

Summary

Function-based views are simple Python functions that handle web requests.

They take a request and return a response like HttpResponse.

Great for small, clear, and direct web page logic.