Python——Django-urls.py的作用


一、urls.py的作用是保存路徑和函數的對應關系

二、函數返回指定內容

from django.urls import path
#引用HTTP協議的代碼
from django.shortcuts import HttpResponse
def yimi(request):
    #request參數保存了所有和用戶瀏覽器請求相關的數據,返回指定內容
    return HttpResponse(r'hello world')
urlpatterns = [
    path('admin/', admin.site.urls),
    #yimi/是瀏覽器的路徑,yimi是函數
    path('yimi/',yimi),
]

三、函數返回頁面

1、使用HttpResponse返回

def xiaohei(request):
    with open("./templates/xiao.html","r",encoding="utf-8") as f:
        data =f.read()
    return HttpResponse(data)

2、使用render返回

from django.shortcuts import render
def xiaohei(request):
    return render(request,"xiao.html")

 3、返回一些提示內容

3.1在HTML里加入 error 是標識符

<p>{{ error }}</p>

3.2使用render 標識符要一直

def xiaohei(request):
    msg = '錯誤'
    return render(request,"zzz.html",{"error":msg})

四、函數跳轉頁面

from django.shortcuts import redirect
def xiaohei(request):
    return redirect("http://www.baidu.com")

 五、引用應用的內容

from 應用名 import views
urlpatterns = [
    path('yimi/',views.yimi)
]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM