2021年11月18日 星期四

Python Django urls .py and views.py(5)

這次練習urls.py
urls.py可指定目前所有連結但需配合著views.py(可自取名字)來顯示
在website資料夾下建立一個views.py
在view.py中寫入function來回傳內容
from django.http import HttpResponse
def home(request):
      return HttpResponse("yes this is your home success!")
接著修改urls.py內容
#原本
from django.contrib import admin
from django.urls import path
urlpatterns = [
     path("admin/", admin.site.urls),
]
#修改後
from django.contrib import admin
from django.urls import path
from website.views import home #要import進來
urlpatterns = [
    #path("admin/", admin.site.urls),
    path("homexx/", home), #(網頁路徑,function)
]
接著瀏覽器輸入
http://127.0.0.1:8000/homexx/
更進階一點views.py加入
def yourinfo(request,name, age):
    return HttpResponse("您的名字{name},您的年齡{age}".format(name = name ,age = age))
修改urls.py
from website.views import home,yourinfo #要import進來
urlpatterns = [
    path("homexx/", home), 
    path("yourinfo/<str:name>/<int:age>",yourinfo),
]
接著瀏覽器輸入
http://127.0.0.1:8000/yourinfo/陳00/35