Introduction
Views in Django decide what happens when someone visits a web page. They take the request and choose what to show back.
Views in Django decide what happens when someone visits a web page. They take the request and choose what to show back.
from django.http import HttpResponse def view_name(request): # process request data # prepare response return HttpResponse('response content')
request parameter holds all information about the user's visit.from django.http import HttpResponse def hello(request): return HttpResponse('Hello, world!')
from django.shortcuts import render def home(request): context = {'name': 'Alice'} return render(request, 'home.html', context)
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.')
This view reads a 'user' name from the URL query and greets them. If no name is given, it says 'Guest'.
from django.http import HttpResponse def greet_user(request): user = request.GET.get('user', 'Guest') return HttpResponse(f'Hello, {user}! Welcome to our site.')
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.
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.
from django.http import HttpResponse
def greet(request):
name = request.GET.get('name', 'Guest')
return HttpResponse(f'Hello, {name}!')/greet?name=Anna?def show(request):
user = request.POST['username']
return HttpResponse(f'User: {user}')Pass the test and this pattern moves unknown