Django view functions and resources

Article directory

    • 1.View
      • 1.1 File or folder
      • 1.2 Relative and absolute import urls
      • 1.3 View parameters
      • 1.4 Return value
      • 1.5 Response header
      • 1.6 FBV and CBV
    • 2. Static resources
      • 2.1 Static files
      • 2.2 Media files

1. View

1.1 File or folder

1.2 Relative and absolute import urls

Note on implementation: Do not make relative imports in the project root directory.

in principle:

  • absolute import
  • Relative import (deep level)

1.3 View parameters

urlpatterns = [
    path('login/', account.login, name="login"),
    path('auth/', order.auth, name='auth'),
]

from django.shortcuts import HttpResponse


def login(request):
    return HttpResponse("login")

What are requests?

Objects, packages, can hold many things.

requests is an object that stores all the content sent to us by the browser, so it contains:
- All data related to the request: currently accessed URL, request method,...
- Additional data added by django
from django.shortcuts import HttpResponse


def login(request):
    # 1. Current URL /api/login/
    print(request.path_info)

    # 2. Parameters passed by URL
    print(request.GET)
    print(request.GET.get("age"))

    # 3. Request method GET/POST
    print(request.method)

    # 4. If post request is made, pass the request body (original data)
    print(
        request.body) # b'{"code":"083Sjmll2yla694F3bll2DguCM2SjmlG","unionId":"oP6QCsyT_9bk1dfSaVf0GEV5Y-yE"}' b'v1=123 & amp;v2=456\ '

    # 4.1 Request body + request header b'v1=123 & amp;v2=456' + content-type:application/x-www-form-urlencoded
    print(request.POST)
    print(request.POST.get("v1"))
    print(request.POST.get("v2"))

    # 4.2 Request body + request header file
    print(request.FILES) #File format + multipart/form-data
    print(request.FILES.get("n1"))
    print(request.FILES.get("n2"))

    # 5. Request header
    # {'Content-Length': '', 'Content-Type': 'text/plain', 'Host': '127.0.0.1:8000', 'Connection ': 'keep-alive', 'Cache-Control': 'max-age=0', 'Sec-Ch-Ua': '" Not A;Brand"; v="99", "Chromium";v="102", "Google Chrome";v="102"', 'Sec-Ch-Ua-Mobile' : '?0', 'Sec-Ch-Ua-Platform': '"macOS"', 'Upgrade-Insecure-Requests': '1', 'User- Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS application/xhtml + xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-User': '?1', \ 'Sec-Fetch-Dest': 'document', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q =0.9,en;q=0.8,zh-TW;q=0.7', 'Cookie': 'csrftoken=CdidpKSGbLxzmOXnbmlkvrZep1eJmKLAA81T73UjcjxEnMOa4YOZqtc849AkYfUy'}
    print(request.headers)

    # 5.1 The request header has a special cookie
    # request.headers['cookie'] # 'csrftoken=CdidpKSGbLxzmOXnbmlkvrZep1eJmKLAA81T73UjcjxEnMOa4YOZqtc849AkYfUy;session=xxxx'
    # {'csrftoken': 'CdidpKSGbLxzmOXnbmlkvrZep1eJmKLAA81T73UjcjxEnMOa4YOZqtc849AkYfUy'}
    print(request.COOKIES)

    # 6.Other values in requests
    print(request.resolver_match)

    return HttpResponse("login")

1.4 Return value

  • HttpResponse
  • JsonResponse
  • render
  • redirect
from django.shortcuts import HttpResponse, redirect, render
from django.http import JsonResponse


def auth(request):
    pass


def login(request):
    # 1. Get request data
    print(request)

    # 2. Judge the conditions based on the request data GET/POST GET.get("xx") POST.get("xx")

    # 3. Return data

    # 3.1 String/byte/text data (picture verification code)
    # return HttpResponse("login")

    # 3.2 JSON format (separation of front-end and back-end, app applet back-end, ajax request)
    # data_dict = {"status": True, 'data': [11, 22, 33]}
    # return JsonResponse(data_dict)

    # 3.3 Redirect
    # return redirect("https://www.baidu.com")
    # return redirect("http://127.0.0.1:8000/api/auth/")
    # return redirect("http://127.0.0.1:8000/api/auth/")
    # return redirect("/api/auth/")
    # return redirect("/api/auth/") # name
    #
    # from django.urls import reverse
    # url = reverse("auth")
    # return redirect(url) # name
    # return redirect("auth")

    # 3.4 Rendering
    # - a. Find 'login.html' and read the content. Question: Where to find it?
    # - By default, search in the path specified by settings.TEMPLATES.DIRS first. (public)
    # - Find the templates directory of each registered app in the registration order, and go to this directory to find 'login.html'
    # - Generally speaking, the principle is to find the template in that app.
    # - b. Render (replace) to get the replaced string
    # - c. Return to browser
    return render(request, 'api/login.html')

1.5 response header

from django.shortcuts import HttpResponse, redirect, render
from django.http import JsonResponse


def login(request):
    res = HttpResponse("login")
    res['xx1'] = "hahaha"
    res['xx2'] = "hahaha"
    res['xx3'] = "hahaha"

    res.set_cookie('k1',"aaaaaaaa")
    res.set_cookie('k2',"bbbbbb")

    return res

1.6 FBV and CBV

  • FBV, views are written in the form of functions. (currently mainstream)
  • CBV, views are written in the form of classes.

Please note that these are just appearances and the essence is exactly the same.

2. Static resources

Static resources:

  • Development needs: css, js, pictures.

    - /static/ of the root directory
    - Already downloaded in the app directory /static/ folder
    
  • Media files: data uploaded by users (excel/pdf/video)

    - /media/ of the root directory
    

2.1 Static files

INSTALLED_APPS = [
    # 'django.contrib.admin',
    # 'django.contrib.auth',
    # 'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    # 'django.contrib.messages',
    'django.contrib.staticfiles',
    "apps.api.apps.ApiConfig",
    "apps.web.apps.WebConfig",
]
...

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
  • Sequence: static folder in the project root directory and static folder in the registered app directory

  • Multi-app development: The pictures of each app are placed in their respective /static/appname/. . .

  • in development process

    • prohibit

      <img src="/static/api/1.png">
      
    • suggestion

      {% load static %}
      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Title</title>
      </head>
      <body>
      <h1>Login page</h1>
      <a href="/xxx/xxxxx/">Replace dao xx</a>
      <a href="{% url 'login' %}">Jump</a>
      
      <img src="{% static 'api/1.png' %}">
      
      </body>
      </html>
      

2.2 Media files

urls.py

from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls.static import static
from django.conf import settings

from apps.api import views


# Many functions, many URLs
urlpatterns = [
    path('api/', include('apps.api.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)