A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 小蜀哥哥 于 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'),
)

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马