0
0
Djangoframework~5 mins

Why views handle request logic in Django

Choose your learning style9 modes available
Introduction

Views in Django decide what happens when someone visits a web page. They take the request and choose what to show back.

When you want to show a web page based on user input.
When you need to get data from a database and display it.
When you want to handle form submissions from users.
When you need to check if a user is logged in before showing content.
When you want to send different responses depending on the request type.
Syntax
Django
from django.http import HttpResponse

def view_name(request):
    # process request data
    # prepare response
    return HttpResponse('response content')
The request parameter holds all information about the user's visit.
Views always return a response, like a web page or a redirect.
Examples
A simple view that returns a plain text greeting.
Django
from django.http import HttpResponse

def hello(request):
    return HttpResponse('Hello, world!')
This view sends data to a template to create a web page.
Django
from django.shortcuts import render

def home(request):
    context = {'name': 'Alice'}
    return render(request, 'home.html', context)
Handles form submission and redirects after success.
Django
from django.http import HttpResponseRedirect

def submit_form(request):
    if request.method == 'POST':
        # process form data
        return HttpResponseRedirect('/thanks/')
    return HttpResponse('Please submit the form.')
Sample Program

This view reads a 'user' name from the URL query and greets them. If no name is given, it says 'Guest'.

Django
from django.http import HttpResponse

def greet_user(request):
    user = request.GET.get('user', 'Guest')
    return HttpResponse(f'Hello, {user}! Welcome to our site.')
OutputSuccess
Important Notes

Views are the place to decide what the user sees or what happens next.

Keep views simple: they should handle requests and responses, not complex logic.

Use Django's built-in helpers like render to make views cleaner.

Summary

Views handle the logic of what to do when a user visits a page.

They take the request, process data, and return a response.

This keeps your web app organized and easy to understand.