[python] Django–templates, static files, django template syntax, requests and responses

The notes are study notes compiled by myself. If there are any mistakes, please point them out~

[Django column]
Django–Introduction to Django, installation of Django, creating projects, and getting started quickly
Django – templates, static files, django template syntax, requests and responses
Django – connect to mysql database

Django–templates, static files, django template syntax, requests and responses

  • templatestemplates
    • Find templates in app order
    • global template
  • static files
    • jquery
    • Bootstrap
  • django template syntax
    • Grammatical features and usage
    • render function in view
    • Example
  • Requests and responses
    • Request
      • 1.Request attributes and methods
      • 2.GET request
      • 3.POST request
    • Response
      • 1.HttpResponse
      • 2.render
      • 3.redirect redirect
    • Error reporting and resolution

templates

Django template is a tool in the Django framework for generating dynamic content. It allows developers to combine Python code and static templates to generate final HTML content. Using Django templates allows developers to insert dynamic data into pages, apply logic to control flow, and reuse common page structures and styles.

In Django, templates are usually used in conjunction with view functions. The view function is responsible for processing business logic and passing data to the template. The template is responsible for rendering the data and generating the final HTML page to return to the user. Through good organization and the use of templates, you can make your web application’s code clearer, easier to maintain, and improve development efficiency.

Find templates in app order


Note: renturn render() [not looking for the current app, but looking for user_list.html according to the registration order of the app]

Global template

Generally speaking, the template that belongs to which app is written under that app. Global templates need to be configured

# Modify setting.py

import os
TEMPLATES = [
    {<!-- -->
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR,'templates')],
        "APP_DIRS": True,
        "OPTIONS": {<!-- -->
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]


Static files

Style sheets (CSS), JavaScript files, images, font files, etc.

When using a web framework like Django, static files are typically stored in the application’s “static” directory. These static files can include CSS files used to beautify the page style, JavaScript files used to enhance interactivity, as well as images, fonts and other resources used by the website.

jquery

jquery download URL: https://releases.jquery.com/jquery/
jquery.3.6.min.js (open the link, copy and paste): https://code.jquery.com/jquery-3.6.0.min.js
Version differences:
Uncompressed: Contains the complete source code without any compression or optimization. Easy to read and debug, the file size is large.

Minified: Reduce file size by removing spaces, comments, and other unnecessary characters. The code is a little more difficult to read and debug.

Slim (lite version): Some less commonly used functions or modules are removed to reduce file size. Only the core functions are retained, and you can add required modules or plug-ins according to your needs.

Slim Minified: The streamlined version performs code compression and removes redundant characters to further reduce the file size.

Bootstrap

Bootstrap Chinese website: https://www.bootcss.com/
Download Bootstrap v3: https://v3.bootcss.com/

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.css'%}">
</head>
<body>
<h1>User list</h1>
<input type="text" class="btn btn-primary" value="New"/>
<img src="{% static 'img/1.png' %}" alt="">

<script src="{% static 'js/jquery.3.6.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>


django template syntax

Grammar features and usage

As a web framework, Django needs a convenient way to dynamically generate HTML. The most common approach relies on templates. The template contains the static portion of the desired HTML output as well as some special syntax describing how to insert dynamic content. Django official documentation on template syntax: https://docs.djangoproject.com/en/3.2/topics/templates/

Here are some important features and usage of Django template syntax:

  1. Variable interpolation:

    • Use the {{ variable name }} syntax in the template to insert the value of the variable.
    • For example:

      {{ title }}

  2. Logical operations:

    • Use the syntax of {% tag %} to perform some logical operations, such as control flow, looping, and logical judgment.
    • For example: {% if condition %} ... {% endif %}
  3. Filter:

    • Filters allow variables to be processed or formatted to meet specific needs.
    • Apply a filter by using | and the filter name after the variable.
    • For example: {{ variable|filter_name }}
  4. Template inheritance:

    • Use the {% extends 'base.html' %} tag to create a template inheritance structure where specific parts of the parent template can be overridden in the child template.
    • For example: use {% block content %} ... {% endblock %} in a child template to overwrite the content in the parent template.
  5. Contains:

    • Use the {% include 'partial.html' %} tag to include other template files into the current template.
    • This can be used to reuse and organize template code.
  6. Loop:

    • Use the syntax {% for item in items %} ... {% endfor %} to perform looping operations.
    • For example: looping through a list or querying data in a collection.
  7. Static file reference:

    • Use the {% static 'path/to/file' %} syntax to reference static files such as CSS, JavaScript, and images.
    • Django manages and serves static files through a static file handler.

This is just a small part of Django’s template syntax, there are many more features and uses. By using template syntax, developers can build flexible and dynamic web pages in Django and separate data from templates for easier maintenance and reuse.

Render function in view

When the render function is used within a view function, it performs the following main operations:

  1. Load template:
    The render function first loads the corresponding template file based on the given template name.

  2. Rendering context:
    Next, the render function combines the incoming data (context) with the loaded template to form the final rendering context.

  3. Rendering template:
    Using the rendering context, the render function will parse and replace variables, tags, filters, etc. in the template to generate the final HTML content.

  4. Create HTTP response:
    Finally, the render function will use the rendered HTML content as the body of the response, generate an HTTP response object, and return it.

Example


views.py

# views.py
def template(request):
    teacher = "Back to back"
    students = ["Quanquan1","Quanquan2","Quanquan3"]
    student_info = {<!-- -->'name':"Quanquan", 'age':18, 'gender':"female"}

    return render(request,"template.html",{<!-- -->
        "t": teacher,
        "s": students,
        "s_info": student_info
    })

template.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Template syntax learning</title>
</head>
<body>
<h4 style="color:red">Variable interpolation:</h4>
<div>teacher:{<!-- -->{ t }}</div><hr/>
<div>students list: {<!-- -->{ s }}</div><hr/>
<div>students0:{<!-- -->{ s.0 }}</div>
<div>students1:{<!-- -->{ s.1 }}</div>
<div>students2:{<!-- -->{ s.2 }}</div><hr/>
<div>name:{<!-- -->{ s_info.name }}</div>
<div>age:{<!-- -->{ s_info.age }}</div>
<div>gender: {<!-- -->{ s_info.gender }}</div>

<h4 style="color:red">Loop:</h4>
<div>
    {% for item in s%}
        <li>{<!-- -->{ item }}</li>
    {% endfor %}
</div><hr/>

<div>
    {% for k,v in s_info.items %}
        <li>{<!-- -->{ k }} : {<!-- -->{ v }}</li>
    {% endfor %}
</div>

<h4 style="color:red">Logical operations:</h4>
<div>
    {% if s_info.name == "circle" %}
        Yes
    {% else %}
        No
    {% endif %}
</div>
</body>
</html>

Requests and Responses

In Django, requests and responses are a very important part of a web application. Here’s a brief explanation of Django requests and responses:

  1. Request:

    • In Django, a request object represents an HTTP request sent by the client to the server. The request object contains various information about the request, such as HTTP method, request headers, path parameters, query parameters, form data, etc.
    • Django’s request object is an instance of the HttpRequest class. You can get the request object through the parameters of the view function and get the required information from it.
  2. Response:

    • The response object represents the server’s reply to the client’s request and contains the content and metadata to be sent back to the client. In Django, a response object is usually an instance of HttpResponse or one of its subclasses.
    • Data can be sent to the client by returning a response object from the view function. The response object can contain HTML content, JSON data, file downloads, etc.

Handling requests and responses in Django typically happens within view functions. The view function receives the request object as a parameter, processes it according to the content of the request, and returns a response object for use by the client. Django also provides many convenient tools and functions to simplify request and response processing, such as decorators, template rendering, redirection, etc., making it easier for developers to build powerful web applications.

Request

1.Request attributes and methods

The HttpRequest object has many properties and methods, the following are some of the commonly used ones:

Attributes:

  • request.method: HTTP request method, such as GET’ or POST’.
  • request.GET: A dictionary-like object that contains all GET parameters.
  • request.POST: A dictionary-like object that contains all POST parameters.
  • request.FILES: A dictionary-like object that contains all uploaded files.
  • request.path: The path of the current request, excluding the domain name part.
  • request.META: A dictionary containing all HTTP header information.
  • request.session: A Session object representing the current session.
  • request.user: User object representing the current authenticated user.

method:

  • request.get(): Get the value of the specified key from the request parameters, and return the default value if the key does not exist.
  • request.getlist(): Gets the value list of the specified key from the request parameter, even if there is only one value, the list is returned.
  • request.is_ajax(): Check whether the request is sent through Ajax.
  • request.is_secure(): Checks whether the request is sent over a secure connection (HTTPS).
  • request.build_absolute_uri(): Build a complete absolute URL.
  • request.is_authenticated(): Checks whether the current user has been authenticated.
  • request.is_anonymous(): Check whether the current user is anonymous.

In addition to the above properties and methods, there are many other properties and methods that can be used to handle HttpRequest objects. You can use these properties and methods in the view function as needed to obtain various requested information, and process and respond accordingly.

2.GET request


Here’s a basic Django view function example when handling a simple GET request:
views.py

# POST method
    if request.method == 'POST':
        # Handle form submission
        name = request.POST.get('name', '')
        email = request.POST.get('email', '')
        print(f'Hello, {<!-- -->name}! email,{<!-- -->email}')
        # Construct context data
        context = {<!-- -->
            'name': name,
            'email': email,
        }
        # Render the template and return the response
        return render(request, 'result.html', context)
    else:
        # Display form page
        return render(request, 'register.html')

register.html

<!DOCTYPE html>
<html>
<head>
    <title>Enter information</title>
</head>
<body>
    <h2>Please enter your information</h2>
    <form method="post" action="/register/">
<!-- {% csrf_token %} is a Django template token used to prevent cross-site request forgery (CSRF) attacks. -->
<!-- Django requires all POST forms to include this tag to ensure security. -->
        {% csrf_token %}
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br><br>
        <input type="submit" value="submit">
    </form>
</body>
</html>

result.html

<!-- result.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Submit results</title>
</head>
<body>
    <h2>Submit results</h2>
    <p>The information you submitted is as follows:</p>
    <p>Name: {<!-- -->{ name }}</p>
    <p>Email: {<!-- -->{ email }}</p>
</body>
</html>

3.POST request

register.html and result.html are the same as the GET method

views.py

# GET method: http://127.0.0.1:8000/register?name=quanquan & amp;[email protected]
    if request.method == 'GET':
        if request.GET.get('name')==None or request.GET.get('email')==None:
            return render(request, 'register.html')
        else:
            name = request.GET.get('name')
            email = request.GET.get('email')
            # Construct context data
            context = {<!-- -->
                'name': name,
                'email': email,
            }
            return render(request, 'result.html', context)

Response

1.HttpResponse

return HttpResponse("Response 1")

2.render

return render(request, 'register.html')

3.redirect redirection

return redirect("https://www.baidu.com")

Error reporting

Error message:
Forbidden (403)
CSRF verification failed. Request aborted.

Error reason:
This error is usually caused by the CSRF protection mechanism in Django. CSRF (Cross-Site Request Forgery) is a network security attack, and Django prevents this type of attack by adding a CSRF tag to the form. When the form is submitted, Django will verify the CSRF tag and will generate this error if the verification fails.

Solution:

  1. Add CSRF tokens in templates: Make sure your form template includes the {% csrf_token %} tag, for example:
<form method="post">
  {% csrf_token %}
  <!-- Other form fields -->
  <input type="submit" value="Submit">
</form>
  1. Use the csrf_exempt decorator: If your view function does not require CSRF protection, you can use the @csrf_exempt decorator on the view function to skip CSRF verification, for example:
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def your_view(request):
    #View function code
  1. Check the middleware settings: Make sure that Django’s CSRF middleware has been correctly added to the MIDDLEWARE settings and is enabled, for example:
MIDDLEWARE = [
    #...
    'django.middleware.csrf.CsrfViewMiddleware',
    #...
]

Using one of the above methods, you should be able to resolve the “CSRF verification failed. Request aborted.” error and successfully submit the form data.