黑马程序员技术交流社区
标题: 【成都校区】Django常用的三个视图基类 [打印本页]
作者: 小蜀哥哥 时间: 2019-12-5 18:03
标题: 【成都校区】Django常用的三个视图基类
本帖最后由 小蜀哥哥 于 2019-12-5 18:03 编辑
常用的通用视图:- View
- TemplateView
- RedirectView
1. django.views.generic.base.View这个类是通用类的基类,其它类都是继承自这个类,一般不会用到这个类,个人感觉用函数更简单些。
[Python] 纯文本查看 复制代码
# views.py
from django.http import HttpResponse
from django.views.generic import View
class MyView(View):
def get(self, request, *args, **kwargs):
return HttpResponse('Hello, World!')
绑定路由:
[Python] 纯文本查看 复制代码
# urls.py
from django.conf.urls import patterns, url
from myapp.views import MyView
urlpatterns = patterns('',
url(r'^mine/$', MyView.as_view(), name='my-view'),
)
2. django.views.generic.base.TemplateView在 get_context_data() 函数中,可以传一些 额外内容 到 模板
[Python] 纯文本查看 复制代码
# views.py
from django.views.generic.base import TemplateView
from articles.models import Article
class HomePageView(TemplateView):
template_name = "home.html"
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['latest_articles'] = Article.objects.all()[:5]
return context
绑定路由
[Python] 纯文本查看 复制代码
# urls.py
from django.conf.urls import patterns, url
from myapp.views import HomePageView
urlpatterns = patterns('',
url(r'^$', HomePageView.as_view(), name='home'),
)
3. django.views.generic.base.RedirectView用来进行跳转, 默认是永久重定向(301),可以直接在urls.py中使用,非常方便:
[Python] 纯文本查看 复制代码
from django.conf.urls import patterns, url
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^go-to-django/$', RedirectView.as_view(url='http://djangoproject.com'), name='go-to-django'),
url(r'^go-to-ziqiangxuetang/$', RedirectView.as_view(url='http://www.ziqiangxuetang.com',permant=False), name='go-to-zqxt'),
)
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |