基础:
from django.urls import path
from testCBV.views import *
app_name='cbv'
urlpatterns = [
path('a', Index.as_view(), name='a'),
]
from django.shortcuts import render,HttpResponse
from django.views.generic.base import View
# Create your views here.
class Index(View):
def get(self,request):
return HttpResponse("1534")
解释:跳转视图
导入:from django.views.generic.base import RedirectView
from django.urls import path
from testCBV.views import *
app_name='cbv'
urlpatterns = [
path('a', Index.as_view(), name='a'),
path('b',Redirect.as_view(),name='b')
]
from django.views.generic.base import RedirectView
class Redirect(RedirectView):
permanent = True
url = None
pattern_name = 'cbv:a'
query_string = True
解释:模板视图
导入:from django.views.generic.base import TemplateView
参数:
class Tem(TemplateView):
extra_context = {'value': "这是jinja2", "jack":"19999999999999999"}
template_name = 'testCBV/index.html'
def get_context_data(self, **kwargs): # 该函数继承父类
context = super().get_context_data(**kwargs)
context['number'] = 555
return context # 其实通俗讲就是给extra_context 里面添加了一个键值对('number':555)
解释:旨在显示数据
解释:需要url里面有一个参数为pk(专门有,为内容id),模板里面用的时候比如views.pymodel = Father
里面对应模板里面就是father
urls.py
urlpatterns = [
path('a', Index.as_view(), name='a'),
path('b', Redirect.as_view(), name='b'),
path('c/' , Tem.as_view(), name='c')
]
views.py
from django.views.generic.detail import DetailView
class Tem(DetailView):
extra_context = {'value': "这是jinja2", "jack":"19999999999999999"}
template_name = 'testCBV/index.html' #注意这个路径问题,应该为/templates/app名字/文件名,不这样的话可以会寻找出错
model = Father
testCBV/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
{{ value }}
{{ number }}
{{ father.name }}
</html>
解释:全部内容显示(可以设置显示多少),记得设置模板里面循环用的名字
urls.py
urlpatterns = [
path('a', Index.as_view(), name='a'),
path('b', Redirect.as_view(), name='b'),
path('c', Tem.as_view(), name='c')
]
views.py
from django.views.generic import ListView
class Tem(ListView):
extra_context = {'value': "这是jinja2", "jack":"19999999999999999"}
template_name = 'testCBV/index.html'#注意这个路径问题,应该为/templates/app名字/文件名,不这样的话可以会寻找出错
context_object_name = 'father' # 模板里面循环用的名字
model = Father
testCBV/index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
{% for article in father %}
<li>{{ article.id }} - {{ article.name }}li>
{% endfor %}
html>
解释:因为现在大多前后端分离,所以下面的内容就属于前后端结合,所以就不详细介绍了
官方文档