建立視圖:
在APP下打開views.py檔案,沒有則建立一個同名檔案,寫入下面内容:
from django.http import HttpResponse
def test1(request):
return HttpResponse("哈哈哈")
urls中配置路由:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('test1/',views.test1),
]
views.test1
是主路由,
test1/
是設定的路由
在浏覽器輸入“http://127.0.0.1:8000/test1/”得到如下結果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxSP9EUTyMGVPhXT61EM4wmYwhGWhxGZzwEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3PnBnauYzMxIzMxcTM1IjMwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
# Create your views here.
def test1(request):
return HttpResponse("doc目錄下的test1")
def test2(request,**kwargs): # 接收從url中傳入的參數
a = kwargs.get("q1")
return HttpResponse("doc目錄下的test2 {}".format(a))
def test3(request):
return redirect("/doc/test1/") # 重定向
def test4(request):
return redirect(reverse("ttt")) # reverse将名字重新解析成位址
def test5(request,age):
return HttpResponse("年齡{}".format(age))
def test6(request):
name = "清單"
return render(request,"doc/list.html",context={"name":name})
render():
def render(request, template_name, context=None, content_type=None, status=None, using=None):
傳回一個HTML頁面
HTML檔案統一放在主目錄的templates 檔案夾中
需在settings中進行配置
TEMPLATES
中的
DIRS
:
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',
],
},
},
]
from django.urls import path
from . import views
路由的設定:
urlpatterns = [
path('test1/', views.test1,name="ttt"),
# name取名,使用reverse将名字重新解析成位址,路徑改變也不需要修改
path('test2/', views.test2,{"q1":"傳參"}),
path('test3/', views.test3),
path('test4/', views.test4),
path('test5/<int:age>/', views.test5), # 使用<>傳參,int為轉換器,限定傳參的類型
path('test6/', views.test6),
預設支援的轉換器:
- str,比對除了路徑分隔符(/)之外的非空字元串,這是預設的形式
- int,比對正整數,包含0。
- slug,比對字母、數字以及橫杠、下劃線組成的字元串。
- uuid,比對格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
- path,比對任何非空字元串,包含了路徑分隔符