Django Views - 網頁的後台邏輯處理

網頁的後台邏輯處理

Posted by 劉啟仲 on Sunday, January 24, 2021

Views所做的事情:

  • 接收用戶請求
    • 決定請求方法 GET, POST….
    • 取得用戶請求內容
  • 資料前處理
    • 取得資料
  • 回應結果
    • 回應一個網頁
    • 回應一個 HTTP CODES
    • 回應 JSON
    • 回應重新導向

VIEWS裝飾子:

範例:使用只有登入後才可以執行dispatch。

class ProtectedView(TemplateView):
 		template_name = 'secret.html'
    
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargw):
      return super().dispatch(*args, **kwargw)

@method_decorator(login_required) - 用戶要登入才可以使用

@never_cache(view_func) - 可以將頁面關閉cache

@require_http_methods([“GET”, “POST”]) - 可規定只能收到哪種需求


建立專案

$ django-admin startproject mysite

目前專案結構

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Run server

$ python manage.py runserver
or
$ python manage.py runserver 8080
or
$ python manage.py runserver 0:8000

建立APP

$ python manage.py startapp polls

目前專案結構,這專案中有init.py檔案,所以在django中,專案是可當作模組的概念,可將整包移植到其他專案中應用。

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
    polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

將polls App放入專案中

編輯 polls/_init_.py

default_app_config = 'polls.apps.PollsConfig'

修改 mysite/settings.py

INSTALLED_APPS = [
    'polls',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Django 文件 - Applications

建立 polls/templates/polls/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>first Django app</title>
</head>
<body>
    <p>Hello, world. You're at the polls index.</p>
</body>
</html>

修改 polls/views.py

from django.shortcuts import render


def index(request):
    return render(request, 'polls/index.html')

建立 polls/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

修改 mysite/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

Run server

$ python manage.py runserver

開啟 http://localhost:8000/polls/ 網頁,看看有沒有顯示Hello, world. You’re at the polls index.


django的幾種回傳方式

回傳Http

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

回傳Json

from django.http import JsonResponse


def index(request):
    return HttpResponse({"Name":"Larry", "email":"aaa@gmail.com"})

回傳html檔案內容

from django.shortcuts import render


def index(request):
    return render(request, 'index.html')