Python Django view 两种return的实现方式
2020-04-03 12:04
513 查看
1.使用render方法
return render(request,'index.html')
返回的页面内容是index.html的内容,但是url不变,还是原网页的url,(比如是login页面的返回方法,跳转后的url还是为login) 一刷新就返回去了
2.使用redirect方法
return redirect(request,'idnex.html')
直接跳转到index.html页面中,url为跳转后的页面url
补充知识:Django的View是如何工作的?
View (视图) 主要根据用户的请求返回数据,用来展示用户可以看到的内容(比如网页,图片),也可以用来处理用户提交的数据,比如保存到数据库中。Django的视图(View)通常和URL路由一起工作的。服务器在收到用户通过浏览器发来的请求后,会根据urls.py里的关系条目,去视图View里查找到与请求对应的处理方法,从而返回给客户端http页面数据。
当用户发来一个请求request时,我们通过HttpResponse打印出Hello, World!
# views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, World!")
下面一个新闻博客的例子。/blog/展示所有博客文章列表。/blog/article/<int:id>/展示一篇文章的详细内容。
# blog/urls.py from django.urls import path from . import views urlpatterns = [ path('blog/', views.index, name='index'), path('blog/article/<int:id>/', views.article_detail, name='article_detail'), ] # blog/views.py from django.shortcuts import render, get_object_or_404 from .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})
模板可以直接调用通过视图传递过来的内容。
# 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的实现方式就是小编分享给大家的全部内容了,希望能给大家一个参考
您可能感兴趣的文章:
相关文章推荐
- Python 实现抽象类的两种方式+邮件提醒+动态导入模块+反射(参考Django中间件源码)
- Python:使用threading模块实现多线程编程二[两种方式起线程]
- python 多线程两种实现方式
- django实现web接口 python3模拟Post请求方式
- python实现快速排序算法(两种不同实现方式)
- TabLayout两种添加tab方式,结合ViewPager+Fragment实现常见界面视图
- python用递归和非递归两种方式实现二分查找
- [转载]python中package机制的两种实现方式
- python中package机制的两种实现方式
- RecycleView设置点击的两种方式:adapter中的onBindViewHolder(VH,int)方法中进行;实现RecyclerView的addonItemTouchListerner()
- python中package机制的两种实现方式
- Python实现图片裁剪的两种方式(Pillow和OpenCV)
- Python实现屏幕截图的两种方式
- 图片轮播器的两种实现方式(ScrollView与collectionView)
- RecyclerView点击事件OnItemClick的两种实现方式
- 用RecyclerView实现新闻列表页,包括头部的图片轮播,两种Item显示方式,下拉刷新和上拉加载以及限制列表的加载条目数
- ListView、RecyclerView 两种方式实现聊天界面支持文字、表情、图片和语音信息,支持下拉加载更多
- 两种实现CircleImageView的方式
- Python3 多线程的两种实现方式
- python中package机制的两种实现方式