小编给大家分享一下Python Django view中使用return的方法有哪些,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

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/
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('blog/', views.index, name='index'),
path('blog/article//', 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的优点有哪些
1、简单易用,与C/C++、Java、C# 等传统语言相比,Python对代码格式的要求没有那么严格;2、Python属于开源的,所有人都可以看到源代码,并且可以被移植在许多平台上使用;3、Python面向对象,能够支持面向过程编程,也支持面向对象编程;4、Python是一种解释性语言,Python写的程序不需要编译成二进制代码,可以直接从源代码运行程序;5、Python功能强大,拥有的模块众多,基本能够实现所有的常见功能。
以上是“Python Django view中使用return的方法有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联成都网站设计公司行业资讯频道!
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页题目:PythonDjangoview中使用return的方法有哪些-创新互联
当前路径:http://www.jxjierui.cn/article/jodjp.html


咨询
建站咨询
