CBV概念:class based view 不是来取代function-based view的,而是为了代码复用和面向对象特性。
Django中,对那些我们平时经常用的View进行了封装,比如用于渲染一个template的TemplateView,用于处理重定向的RedirectView,用于处理表单的FormView,用于处理数据库对象的DetailView和ListView等,这些View有一个共同的父类:View,在这个View类中,向外暴露了一个类方法:as_view(),它返回一个方法,这就是所有的View类的入口。
context详解:本质就是一组用字典封装好的准备送给template的参数,在view和template中扮演桥梁的角色。
from django.http import HttpResponse
def my_view(request):
if request.method == 'GET':
# <view logic>
return HttpResponse('result')
对比而言,CBV如下:
from django.http import HttpResponse
from django.views.generic import View
class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')
在urls.py中,如下写法:
from django.conf.urls import url from myapp.views import MyView
urlpatterns = [
url(r'^about/$', MyView.as_view()), ]
from django.http import HttpResponse
from django.views.generic import View
class GreetingView(View):
greeting = "Good Day"
def get(self, request):
return HttpResponse(self.greeting)
class MorningGreetingView(GreetingView):
greeting = "Morning to ya"
处理表格form的例子如下:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import MyForm
def myview(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
# <process form cleaned data>
return HttpResponseRedirect('/success/')
else:
form = MyForm(initial={'key': 'value'})
return render(request, 'form_template.html', {'form': form})
类似的CBV:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
from .forms import MyForm
class MyFormView(View):
form_class = MyForm
initial = {'key': 'value'}
template_name = 'form_template.html'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
# <process form cleaned data>
return HttpResponseRedirect('/success/')
django相关命令:django-admin(.py) startproject mysite,就会看到如下的项目目录样式,
mysite
├── manage.py
└── mysite
├── init.py
├── settings.py
├── urls.py
└── wsgi.py
然后在外层的mysite目录中执行 python manage.py startapp learn 可以看到mysite中多了一个learn文件夹。
learn/
├── init.py
├── admin.py
├── models.py
├── tests.py
└── views.py
此时learn作为一个app已经建立,再将其加入到settings.py的INSTALL_APP中。修改mysite/mysite/settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'learn',
)
新建的 app 如果不加到 INSTALL_APPS 中的话, django 就不能自动找到app中的模板文件(app-name/templates/下的文件)和静态文件(app-name/static/中的文件)
一 基本视图
1.django.views.generic.base.View
通用类的基类
# 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!')
# 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'),
)
- django.views.generic.base.TemplateView
在get_context_data() 函数中,可以传一些 额外内容 到 模板
# 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
# urls.py
from django.conf.urls import patterns, url
from myapp.views import HomePageView
urlpatterns = patterns('',
url(r'^$', HomePageView.as_view(), name='home'),
)
- django.views.generic.base.RedirectView
永久定向,可以直接在urls中使用
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'),
)
其他使用方法:
# views.py
from django.shortcuts import get_object_or_404
from django.views.generic.base import RedirectView
from articles.models import Article
class ArticleCounterRedirectView(RedirectView):
url = ' # 要跳转的网址,
# url 可以不给,用 pattern_name 和 get_redirect_url() 函数 来解析到要跳转的网址
permanent = False #是否为永久重定向, 默认为 True
query_string = True # 是否传递GET的参数到跳转网址,True时会传递,默认为 False
pattern_name = 'article-detail' # 用来跳转的 URL, 看下面的 get_redirect_url() 函数
# 如果url没有设定,此函数就会尝试用pattern_name和从网址中捕捉的参数来获取对应网址
# 即 reverse(pattern_name, args) 得到相应的网址,
# 在这个例子中是一个文章的点击数链接,点击后文章浏览次数加1,再跳转到真正的文章页面
def get_redirect_url(self, *args, **kwargs):
If url is not set, get_redirect_url() tries to reverse the pattern_name using what was captured in the URL (both named and unnamed groups are used).
article = get_object_or_404(Article, pk=kwargs['pk'])
article.update_counter() # 更新文章点击数,在models.py中实现
return super(ArticleCounterRedirectView, self).get_redirect_url(*args, **kwargs)
# urls.py
from django.conf.urls import patterns, url
from django.views.generic.base import RedirectView
from article.views import ArticleCounterRedirectView, ArticleDetail
urlpatterns = patterns('',
url(r'^counter/(?P<pk>\d+)/$', ArticleCounterRedirectView.as_view(), name='article-counter'),
url(r'^details/(?P<pk>\d+)/$', ArticleDetail.as_view(), name='article-detail'),
)
二 通用显示视图:
1. django.views.generic.detail.DetailView
DetailView 有以下方法:
dispatch()
http_method_not_allowed()
get_template_names()
get_slug_field()
get_queryset()
get_object()
get_context_object_name()
get_context_data()
get()
render_to_response()