类视图
- View
- TemplateView
- 多继承的子类
- View
- ContextMixin
- 接收上下文
- 从视图函数传递到模板的内容
- 函数 get_context_data
- TemplateResponseMixin
- 将内容渲染到模板中
- template_name
- template_engine
- response_class
- content_type
- 函数 render_to_response
- ListView
- MultipleObjectTemplateResponseMixin
- TemplateResponseMixin
- 获取模板名字
- 首先根据template_name
- 如果没找到
- 自己根据 应用的名字,关联模型的名字, _list.html 去查找
- App/book_list.html
- BaseListView
- MultipleObjectMixin
- ContextMixin
- get_queryset
- model
- View
- 默认实现了get,渲染成了response
- DetailView
- SingleObjectTemplateResponseMixin
- TemplateResponseMixin
- 重写了获取模板名字的方法
- BaseDetailView
1、urls.py
from django.conf.urls import url
from App import views
urlpatterns = [
url(r'^hello/', views.HelloView.as_view(), name='hello'),
# url(r'^template/', views.HelloTemplateView.as_view(template_name='hello.html'), name='template'),
url(r'^template/', views.HelloTemplateView.as_view(), name='template'),
url(r'^listview/', views.HelloListView.as_view(), name='listview'),
url(r'^single/(?P<pk>\d+)/', views.HeDetailView.as_view(), name='single'),
]
2、models.py
from django.db import models
class Book(models.Model):
b_name = models.CharField(max_length=32)
3、views.py
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView, ListView, DetailView
from App.models import Book
class HelloView(View):
def get(self, request):
return render(request, 'hello.html')
class HelloTemplateView(TemplateView):
template_name = 'hello.html'
class HelloListView(ListView):
template_name = 'BookList.html'
model = Book
class HeDetailView(DetailView):
# template_name = 'Book.html'
# model = Book
queryset = Book.objects.all()
4、templates-》Book.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Book</title>
</head>
<body>
<h2>{{ book.b_name }}</h2>
</body>
</html>
5、templates-》BookList.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BookList</title>
</head>
<body>
<ul>
{% for book in object_list %}
<li><a href="{% url 'cbv:single' pk=book.id %}">{{ book.b_name }}</a></li>
{% endfor %}
</ul>
</body>
</html>
6、templates-》App-》book_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BookDetail</title>
</head>
<body>
<h2 style="color: green">{{ book.b_name }}</h2>
</body>
</html>