Python Django view 兩種return的實(shí)現(xiàn)方式
1.使用render方法
return render(request,’index.html’)
返回的頁(yè)面內(nèi)容是index.html的內(nèi)容,但是url不變,還是原網(wǎng)頁(yè)的url,(比如是login頁(yè)面的返回方法,跳轉(zhuǎn)后的url還是為login) 一刷新就返回去了
2.使用redirect方法
return redirect(request,’idnex.html’)
直接跳轉(zhuǎn)到index.html頁(yè)面中,url為跳轉(zhuǎn)后的頁(yè)面url
補(bǔ)充知識(shí):Django的View是如何工作的?
View (視圖) 主要根據(jù)用戶的請(qǐng)求返回?cái)?shù)據(jù),用來(lái)展示用戶可以看到的內(nèi)容(比如網(wǎng)頁(yè),圖片),也可以用來(lái)處理用戶提交的數(shù)據(jù),比如保存到數(shù)據(jù)庫(kù)中。Django的視圖(View)通常和URL路由一起工作的。服務(wù)器在收到用戶通過(guò)瀏覽器發(fā)來(lái)的請(qǐng)求后,會(huì)根據(jù)urls.py里的關(guān)系條目,去視圖View里查找到與請(qǐng)求對(duì)應(yīng)的處理方法,從而返回給客戶端http頁(yè)面數(shù)據(jù)。
當(dāng)用戶發(fā)來(lái)一個(gè)請(qǐng)求request時(shí),我們通過(guò)HttpResponse打印出Hello, World!
# views.pyfrom django.http import HttpResponsedef index(request): return HttpResponse('Hello, World!')
下面一個(gè)新聞博客的例子。/blog/展示所有博客文章列表。/blog/article/<int:id>/展示一篇文章的詳細(xì)內(nèi)容。
# blog/urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [ path(’blog/’, views.index, name=’index’), path(’blog/article/<int:id>/’, views.article_detail, name=’article_detail’),]# blog/views.pyfrom django.shortcuts import render, get_object_or_404from .models import Article# 展示所有文章def index(request): latest_articles = Article.objects.all().order_by(’-pub_date’) return render(request, ’blog/article_list.html’, {'latest_articles': latest_articles})# 展示所有文章def article_detail(request, id): article = get_object_or_404(Article, pk=id) return render(request, ’blog/article_detail.html’, {'article': article})
模板可以直接調(diào)用通過(guò)視圖傳遞過(guò)來(lái)的內(nèi)容。
# blog/article_list.html{% block content %}{% for article in latest_articles %} {{ article.title }} {{ article.pub_date }}{% endfor %}{% endblock %}# blog/article_detail.html{% block content %}{{ article.title }}{{ article.pub_date }}{{ article.body }}{% endblock %}
以上這篇Python Django view 兩種return的實(shí)現(xiàn)方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5動(dòng)態(tài)(可拖動(dòng)控件大小)布局控件QSplitter詳細(xì)使用方法與實(shí)例2. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)3. js開(kāi)發(fā)中的頁(yè)面、屏幕、瀏覽器的位置原理(高度寬度)說(shuō)明講解(附圖)4. CSS清除浮動(dòng)方法匯總5. 不要在HTML中濫用div6. XML入門(mén)的常見(jiàn)問(wèn)題(三)7. Python數(shù)據(jù)分析JupyterNotebook3魔法命令詳解及示例8. ASP動(dòng)態(tài)include文件9. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫(xiě)金額)的函數(shù)10. vue跳轉(zhuǎn)頁(yè)面常用的幾種方法匯總
