Python Django view 兩種return的實(shí)現(xiàn)方式
1.使用render方法
return render(request,’index.html’)
返回的頁面內(nèi)容是index.html的內(nèi)容,但是url不變,還是原網(wǎng)頁的url,(比如是login頁面的返回方法,跳轉(zhuǎn)后的url還是為login) 一刷新就返回去了
2.使用redirect方法
return redirect(request,’idnex.html’)
直接跳轉(zhuǎn)到index.html頁面中,url為跳轉(zhuǎn)后的頁面url
補(bǔ)充知識(shí):Django的View是如何工作的?
View (視圖) 主要根據(jù)用戶的請求返回?cái)?shù)據(jù),用來展示用戶可以看到的內(nèi)容(比如網(wǎng)頁,圖片),也可以用來處理用戶提交的數(shù)據(jù),比如保存到數(shù)據(jù)庫中。Django的視圖(View)通常和URL路由一起工作的。服務(wù)器在收到用戶通過瀏覽器發(fā)來的請求后,會(huì)根據(jù)urls.py里的關(guān)系條目,去視圖View里查找到與請求對應(yīng)的處理方法,從而返回給客戶端http頁面數(shù)據(jù)。
當(dāng)用戶發(fā)來一個(gè)請求request時(shí),我們通過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)用通過視圖傳遞過來的內(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)方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. idea設(shè)置提示不區(qū)分大小寫的方法2. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))3. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)4. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容5. css代碼優(yōu)化的12個(gè)技巧6. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法7. 原生JS實(shí)現(xiàn)記憶翻牌游戲8. Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)9. CentOS郵件服務(wù)器搭建系列—— POP / IMAP 服務(wù)器的構(gòu)建( Dovecot )10. django創(chuàng)建css文件夾的具體方法
