Django Views Fundamentals: Understanding the core of a web application
Hello, fellow Django users! Today we'll be discussing Django If you're just getting started with Django, you know how important Views are.
Views are the brains of Django, processing the user's requests and returning responses. Sounds complicated? Don't worry, this post will make it easy and fun to learn. So, let's get started!
What are Django Views?
Django Views uses the The part of your web application that handles logicWhen a user sends a request via a URL, Views is responsible for taking that request, processing it, and returning the appropriate response. In short, Views is the function that determines the content of a web page.

Django Views Fundamentals - Creating Functional Views
In its most basic form, a View is a function. Let's create one.
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello, Django world!")This simple function is View. request object and passes it to the HttpResponsefor the first time.
Code commentary
1.
from django.http import HttpResponse
- Meaning: Django's
django.httpIn the moduleHttpResponseGet the class.- Description.:
HttpResponseis a class used to generate HTTP responses in Django. It allows you to return text, HTML, JSON, and more to clients (e.g., web browsers).2.
def hello_world(request):
- Meaning:
hello_worldDefine a view function named- Description.: In Django, a view function is a function that takes an HTTP request and returns an HTTP response. This function uses the
requestobject as a parameter.requestobject contains HTTP request information (such as headers, cookies, GET/POST data, etc.) sent from the client.3.
return HttpResponse("Hello, Django world!")
- Meaning:
HttpResponseobject and returns it.- Description.: This line returns an HTTP response containing the string "Hello, Django world!". This string is sent to the client (e.g., a web browser) and displayed on the screen.

Django Views Fundamentals - Associating URLs with Views
Once you've created your View, you'll need to associate it with a URL. urls.py Try writing something like this in your file
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello_world, name='hello'),
]Now, the /hello/ URL and the View we created should work.
Code commentary
1.
from django.urls import path
- Meaning: Django's
django.urlsIn the modulepathGet the function.- Description.:
pathfunction is used to define a URL pattern. The function takes two required arguments (URL pattern and view function) and an optional argument (name).2.
from . import views
- Meaning: The current directory (or current app)'s
views.pyImport everything from the file.- Description.:
views.pyThe file contains view functions (e.g:hello_world) is defined. You can import this file to associate a URL with a view function.3.
urlpatterns = [ ... ]
- Meaning: A list that defines the URL pattern.
- Description.: Django uses
urlpatternsto map URLs to view functions. The URLs are searched in the order defined in this list, and if a matching URL pattern is found, the corresponding view function is executed.4.
path('hello/', views.hello_world, name='hello')
- Meaning:
/hello/URL pattern to theviews.hello_worldConnect with a view function.- Description.:
'hello/': represents a URL pattern. In this case,/hello/to execute this view function.views.hello_world: Specifies the view function to be mapped to this URL pattern.views.pyfile defined in thehello_worldfunction on the function.name='hello': Give this URL pattern a name. This name is used when dynamically generating URLs in a template or view. For example,{% url 'hello' %}for use in templates, such asOverall behavior
- When a user opens the
/hello/URL.- Django uses the
urlpatternsTraverse the list and use the/hello/Look for patterns.- If a matching pattern is found,
views.hello_worldRun the view function.hello_worldThe view function is aHttpResponse("Hello, Django world!")for the new value.- The client (web browser) displays the message "Hello, Django world!" on the screen.
Django Views basics - Rendering templates
What if you want to return an HTML page instead of just text? You can use Django's template system:
from django.shortcuts import render
def home(request):
context = {'message': 'Welcome!'}
return render(request, 'home.html', context)This View uses the home.html Render the template, context Pass the data from the dictionary to the template.
Code commentary
1.
from django.shortcuts import render
- Meaning: Django's
django.shortcutsIn the modulerenderGet the function.- Description.:
renderfunction is a convenient tool for rendering a template and returning an HTTP response. The function takes three arguments
request: HTTP request object.template_name: Path to the template file to render.context(optional): A dictionary containing data to pass to the template.2.
def home(request):
- Meaning:
homeDefine a view function named- Description.: This function receives an HTTP request from the client (
request), process it, and return an HTTP response. In Django, every view function takes arequestobject.3.
context = {'message': 'Welcome!'}
- Meaning:
contextand create a dictionary called'message'key to"Welcome!to the value of- Description.:
contextis a dictionary that holds data to pass to the template. This data can be used dynamically in the template. For example,{{ message }}is used as a variable in the template.4.
return render(request, 'home.html', context)
- Meaning:
renderfunction to use thehome.htmlRender the template, and return the result in an HTTP response.- Description.:
request: HTTP request object.'home.html': The path to the template file to render. Django uses thetemplatesdirectory and locate this file.context: A dictionary containing the data to pass to the template.Overall behavior
- When a user opens the
/home/URL.- Django uses the
homeRun the view function.homeThe view function is acontextCreate a dictionary,'message'key to"Welcome!to the value ofrenderfunction is ahome.htmlWhen rendering a templatecontextPass the data.- The template engine uses the
home.htmlfile and process it,{{ message }}part to"Welcome!to replace the- The final rendered HTML is sent to the client and displayed on the screen.
Django Views Fundamentals - Handling dynamic URL parameters
If you want to dynamically get a value from a URL and process it, you can do this:
def greet_user(request, username):
return HttpResponse(f"Hello, {username}!")And the urls.pyIn:
path('greet//', views.greet_user, name='greet'),Now, the /greet/retract/and you'll see a message that says, "Hello, Chul-Soo!"

Django Views Fundamentals - Handling HTTP methods
You can handle a variety of HTTP methods (GET, POST, etc.) in View:
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"])
def my_view(request):
@require_http_methods. if request.method == 'GET':
Process a # GET request
return HttpResponse("We received your GET request.")
elif request.method == 'POST':
Handle a # POST request
return HttpResponse("We received your POST request.")This View only accepts GET and POST requests, and handles them differently.
Code commentary
1.
from django.views.decorators.http import require_http_methods
- Meaning: Django's
django.views.decorators.httpIn the modulerequire_http_methodsGet the decorator.- Description.:
require_http_methodsis a decorator that restricts the view function to only handle certain HTTP methods (GET, POST, PUT, DELETE, etc.). If a request comes in with a disallowed method, a405 Method Not AllowedReturns the response.2.
@require_http_methods(["GET", "POST"])
- Meaning:
my_viewSet the view function to accept only GET and POST methods.- Description.: This decorator is applied to the view function,
["get", "post"]Allow only the methods specified in the list. If a request comes in with a different method (e.g. PUT, DELETE), the405 Method Not AllowedReturns an error.3.
def my_view(request):
- Meaning:
my_viewDefine a view function named- Description.: This function returns an HTTP request (
request), and return the appropriate HTTP response. In Django, every view function takes arequestobject.4.
if request.method == 'GET':
- Meaning: Verify that the request method is GET.
- Description.:
request.methodindicates the HTTP method of the current request (GET, POST, etc.). This conditional statement is only executed if the request is a GET method.5.
return HttpResponse("The GET request was received.")
- MeaningReturns an HTTP response with the message "GET request received".
- Description.:
HttpResponseis the class that generates the HTTP response in Django. In this case, it returns a simple text response.6.
elif request.method == 'POST':
- Meaning: Check if the request method is POST.
- Description.: This conditional statement is only executed if the request is a POST method.
7.
return HttpResponse("We received a POST request.")
- MeaningReturns an HTTP response with the message "POST request received".
- Description.: Returns this message when a POST request comes in.
Overall behavior
- If the client is a
my_viewSend a GET or POST request to a view function.@require_http_methods(["GET", "POST"])The decorator checks to see if the request method is GET or POST.
- If it is an allowed method (GET, POST), the view function is executed.
- The method is not allowed (for example, PUT, DELETE),
405 Method Not AllowedReturns an error.- Inside a view function
request.methodto process the GET or POST request.
- For GET requests: Return the message "GET request received".
- For POST requests: Return the message "We received your POST request".
Django Views Fundamentals - Interacting with the Database
You can pull data from the database and use it in View:
from django.shortcuts import render
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books': books})This View gets all the Book objects and passes them to the template.
Code commentary
from django.shortcuts import render
- Import the render function from Django's shortcuts module.
- The render function is a convenient function that loads a template and returns an HttpResponse object with context data.
from .models import Book
- Import the Book model from the current app's models.py file.
- '.' means the current directory.
def book_list(request):
- Define a view function called book_list.
- This function takes an HTTP request (request) as a parameter.
books = Book.objects.all()
- Fetch all objects in the Book model from the database and store them in the books variable.
all()method returns all records in the model as a queryset.return render(request, 'book_list.html', {'books': books})
- Generate an HTTP response using the render function.
- The first argument
requestis the original HTTP request object.- The second argument
'book_list.html'is the name of the template file to use.- The third argument
{'books': books}is the context data to pass to the template. Here, we pass the books queryset with the key 'books'.
Django Views Fundamentals - Handling redirects
Sometimes you need to redirect users to a different page:
from django.shortcuts import redirect
def redirect_view(request):
return redirect('home') # 'home' is the name of the URLThis View redirects the user to a URL named "home".
Code commentary
from django.shortcuts import redirect
- Import the redirect function from Django's shortcuts module.
- The redirect function is a handy function used to redirect a user to another page.
def redirect_view(request):
- Define a view function called redirect_view.
- This function takes an HTTP request (request) as a parameter.
return redirect('home')
- Use the redirect function to redirect the user to a URL named 'home'.
- 'home' is the URL name defined in Django's URL settings.
- This function generates an HTTP redirect response.
Wrapping up the Django Views basics
So far, we've covered the basics of Django Views. Views are the heart of a Django application: handling user requests, processing data, and returning responses all happen in Views.
It may seem complicated at first, but if you take it one step at a time, you'll master it in no time. Keep practicing and experimenting. Once you've mastered Django Views, your web development skills will take off.
By the way, an equally important concept to Django Views is Models, right? Django Models Fundamentals: A complete guide to understanding database structure with ease post to build on that foundation!
Glossary
- ViewPython function to process user requests and return a response
- URLconf: Setup to associate a URL pattern with a View
- HttpResponse: the response object returned by the View
- render(): Function that fetches a template and returns it as an HttpResponse object
- Dynamic URLs: How to include variables in URLs and handle them dynamically
- HTTP MethodsHow the client makes requests to the server: GET, POST, etc.
- ORMObject-Relational Mapping, a tool that makes it easy to work with databases in Django
Django Views, you're a little familiar with it now, right? Once you master Views, you can build anything with Django. Keep learning and practicing. We wish you the best on your Django journey!







