Django小筆記-檢視,模板
檢視的基本使用
概述 在django中,檢視對web請求進行迴應 檢視就是一個python函式,在view.py檔案中定義
定義檢視 from django.http import HttpResponse def index(request): #request:請求體(就是瀏覽器給伺服器的東西) return HttpResponse("sunck good")
配置url 修改project.py目錄下的url.py檔案 from django.conf.urls import url from django.contrib import admin from django.conf.urls import include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^", include('myApp.urls')) #引入myApp下的urls.py # 檔案 ]
在myApp應用目錄下建立一個url.py檔案 from django.conf.urls import url from . import views #引入當前目錄下的views urlpatterns = [ url(r"$",views.index()) #引入views下的index.py檔案 ]
模板的基本使用
概述:模板是html頁面,可以根據檢視中傳遞過來的資料進行填充
建立模板:在1_project\projectd的目錄下建立templates資料夾(myApp、project、manage.py的同級目錄),然後在templates資料夾下建立對應專案的模板(day34\1_project\project\templates\myApp)
配置模板路徑 修改settings.py檔案下的TEMPLATES TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], #新增模板目錄 'APP_DIRS': True,
定義模板 在templates\myApp下建立grades.html、students.html檔案
模板語法 {{輸出值,可以是變數,也可以是物件.屬性}} {{%執行程式碼段%}}
http://127.0.0.1:8000/grades 1、寫grades.html模板 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>班級資訊</title> </head> <body> <h1>班級資訊列表</h1> <!--[python04,python04,python06]--> {%for grade in grades%} <li> <a href="#">{{grade.gname}}</a> </li> {%endfor%} </body> </html>