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 기초 참고 이미지 - 로직 처리
(Django Views Basics Reference Image - Logic Processing )

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.http In the module HttpResponse Get 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):
  • Meaninghello_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 request object as a parameter. request object contains HTTP request information (such as headers, cookies, GET/POST data, etc.) sent from the client.
3. return HttpResponse("Hello, Django world!")
  • MeaningHttpResponse object 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의 주요 유형과 기능
(Main types and features of Django Views)

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.urls In the module path Get the function.
  • Description.path function 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.py Import everything from the file.
  • Description.views.py The 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 the views.hello_world Connect 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.py file defined in the hello_world function 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 as
Overall behavior
  1. When a user opens the /hello/ URL.
  2. Django uses the urlpatterns Traverse the list and use the /hello/ Look for patterns.
  3. If a matching pattern is found, views.hello_world Run the view function.
  4. hello_world The view function is a HttpResponse("Hello, Django world!")for the new value.
  5. 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.shortcuts In the module render Get the function.
  • Description.render function is a convenient tool for rendering a template and returning an HTTP response. The function takes three arguments
    1. request: HTTP request object.
    2. template_name: Path to the template file to render.
    3. context (optional): A dictionary containing data to pass to the template.
2. def home(request):
  • MeaninghomeDefine 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 a request object.
3. context = {'message': 'Welcome!'}
  • Meaningcontextand 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)
  • Meaningrender function to use the home.html Render 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 the templates directory and locate this file.
    • context: A dictionary containing the data to pass to the template.
Overall behavior
  1. When a user opens the /home/ URL.
  2. Django uses the home Run the view function.
  3. home The view function is a context Create a dictionary, 'message' key to "Welcome!to the value of
  4. render function is a home.html When rendering a template context Pass the data.
  5. The template engine uses the home.html file and process it, {{ message }} part to "Welcome!to replace the
  6. 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!"

실제 View 작동 방식 시퀀스 다이어그램
(Sequence diagram of how View works in action)

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.http In the module require_http_methods Get 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, a 405 Method Not Allowed Returns the response.
2. @require_http_methods(["GET", "POST"])
  • Meaningmy_view Set 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), the 405 Method Not Allowed Returns an error.
3. def my_view(request):
  • Meaningmy_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 a request object.
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
  1. If the client is a my_view Send a GET or POST request to a view function.
  2. @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 Allowed Returns an error.
  3. 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

  1. 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.
  2. from .models import Book
    • Import the Book model from the current app's models.py file.
    • '.' means the current directory.
  3. def book_list(request):
    • Define a view function called book_list.
    • This function takes an HTTP request (request) as a parameter.
  4. 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.
  5. 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 URL

This View redirects the user to a URL named "home".

Code commentary

  1. 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.
  2. def redirect_view(request):
    • Define a view function called redirect_view.
    • This function takes an HTTP request (request) as a parameter.
  3. 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!

테리 이모티콘
(Happy coding!)

Similar Posts