In Django, a view is a function that receives a web request and returns a web response. Function-based views (FBVs) are the most straightforward type of view, where a Python function is mapped to a URL pattern and is responsible for returning an HTTP response.
# Import HttpResponse class
from django.http import HttpResponse
def my_view(request):
# Return simple HTTP response
return HttpResponse("Hello, World!")
# URL configuration file
from django.urls import path
from . import views
urlpatterns = [
# Map URL to view function
path('hello/', views.my_view, name='hello'),
]
# Render HTML template
from django.shortcuts import render
def home_view(request):
return render(request, 'home.html', {'greeting': 'Hello, World!'})
# Return JSON response
from django.http import JsonResponse
def api_view(request):
data = {'message': 'Hello, World!'}
return JsonResponse(data)
path() in urls.pyChange the message inside HttpResponse() and refresh the browser to see instant updates.