1. 程式人生 > 其它 >Django學習記錄4

Django學習記錄4

Django連線一個前端頁

1.在專案目錄下建立一個資料夾存放html檔案(也可以在應用目錄下)

編寫html檔案

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <
title>Django檢視層</title> </head> <body> <h2>Djando檢視</h2> <ul> <!-- <li><a href="resp01">一個簡單檢視</a></li> --> <!-- 地址可以是直接寫,也可以用下邊方式反向解析名為aa的地址,在urls中設定 --> <li><a href="{% url 'aa' %}">一個簡單檢視</
a></li> <li><a href="{% url 'json01' %}">json</a></li> <li><a href="{% url 'rescookie' %}">cookie</a></li> </ul> </body> </html>

2.編寫好的html檔案需要設定地址,在settings檔案裡設定:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates
', 'DIRS': [os.path.join(BASE_DIR,"templates")], #設定新增index.html地址,存放在專案目錄下的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', ], }, }, ]

3.在views.py檔案新增響應內容

from django.shortcuts import render
from django.http import HttpResponse , JsonResponse
# Create your views here.
import hashlib

def index(request):
    return render(request, "myapp/index.html")
  #響應的內容為templates目錄下myapp/index.html templates在之前已經宣告
def resp01(request): return HttpResponse("<h3>檢視響應</h3>") #HttpResponse可以響應html語言 def resp02(request): data = [ {"id" : 1, "name" : "zhangsan", "age" : 20}, {"id" : 2, "name" : "lisi", "age" : 21}, {"id" : 3, "name" : "wangwu", "age" : 20}, ] return JsonResponse({"data" : data})

#JsonResponse不能直接輸出data,應轉化為json格式 def resp03(requset): response = HttpResponse("cookie設定") rescookie = "flag_jdf34hfh9dfd3" m = hashlib.md5() m.update(rescookie.encode(encoding="UTF-8")) t = m.hexdigest() response.set_cookie("cookie", t)#向前端傳遞一個名為"cookid"內容為t的值 return response
#前端點選連結,當伺服器迴應時會為前端傳遞一個cookid值

編輯好views.py檔案後需要在應用目錄下新增urls.py檔案,傳遞views裡的index、resp01、resp02、resp03引數.

from django.urls import path , include
from myapp import views
urlpatterns = [
    
    path("",views.index),
    path("resp01",views.resp01,name = "aa"),
#"aa"將resp01地址命名,在其他地方可以直接引用反向解析地址,當原地址發生變更時它也會
隨之變化,可以增強程式碼靈活性。 path(
"resp02",views.resp02,name = "json01"), path("resp03",views.resp03,name = "rescookie"), ]