Django URL和View的關(guān)系說明
1、每次用戶發(fā)來一個HttpRequest請求,Django會用URL_pattern與請求進(jìn)行匹配,匹配到第一個URL_pattern就會把請求轉(zhuǎn)向?qū)?yīng)的view
2、view用來響應(yīng)request,并返回response,response里可以包含網(wǎng)頁文件呀,圖片等等。所以項(xiàng)目中絕大部分代碼均在此編寫。
view 可以引入通用模板來減少代碼量,具體查看文檔
Use generic views
3、view引入HTML文件的方法:
在一個app下建立一個templates文件夾,將html文件放進(jìn)去該文件夾
這里其實(shí)不一定要把HTML文件放在這個templates里,可以隨意定義
不過,需要在setting.py里,找到templates,
修改DIRS:[ os.path.join (BASE_DIR,’你定義的html存放的文件夾’)]
在app下 view.py 文件,在里面寫好view函數(shù)
def 函數(shù)名(request):
return render(request,’index.html’)
render(渲染)需要三個變量, 第一個變量是request請求,第二個是模版所在目錄,第三個是一個字典(可選),字典用于對應(yīng)模板里設(shè)計(jì)的變量,可以用locals()將函數(shù)里設(shè)計(jì)的變量自動轉(zhuǎn)換為字典
4、在對于app下創(chuàng)建一個urls.py ,寫入如下內(nèi)容
from django.urls import pathfrom . import viewsurlpatterns = [ path(’’, views.index, name=’index’),]
5、在項(xiàng)目文件夾里找到 urls.py 加入如下內(nèi)容
from django.urls import include, pathurlpatterns = [ path(’polls/’, include(’polls.urls’)), path(’admin/’, admin.site.urls),]
對于<a>標(biāo)簽里的 href 可以用 {% url ’url名’ %}來代替,url名指的是 urls.py 里的path(’login.html/’, views.my_login, name=’url名’),
Django 中通常使用 get_object_or_404()來捕捉 404 錯誤,而不用自己寫 try...except
def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, ’polls/detail.html’, {’question’: question})
補(bǔ)充:django中url與view配置方法
django中url與view配置方法(一)url.py
from django.conf.urls import urlfrom . import viewsurlpatterns = [ url(r’^$’, views.showAssets, name=’show_assets’),]
views.py
# -*- coding: utf-8 -*-from django.shortcuts import render_to_response# Create your views here.def showAssets(request): return render_to_response(’assets_index.html’, {})django中url與view配置方法(二)
url.py
# -*- coding: utf-8 -*-from django.conf.urls import urlfrom app001.views import IndexViewurlpatterns = [ url(r’^admin/’, admin.site.urls), url(r’^$’, IndexView.as_view(), name='index'), ]
views.py
# -*- coding: utf-8 -*-from django.views.generic.base import Viewfrom django.shortcuts import render# Create your views here.class IndexView(View): def get(self, request): return render(request, ’index.html’, {})
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項(xiàng)目的過程2. ASP中常用的22個FSO文件操作函數(shù)整理3. ASP編碼必備的8條原則4. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp5. 三個不常見的 HTML5 實(shí)用新特性簡介6. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析7. SharePoint Server 2019新特性介紹8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. php測試程序運(yùn)行速度和頁面執(zhí)行速度的代碼
