Django学习笔记(9)cvb和fvb
CVB和FVB
  CVB 即class view    FVB  即function view  ,主要⽤来在视图views.py 的两种写法,⼀般有GET  POST  PUT DELETE等请求⽅式 
  注意:form表单需要处理crsf,不然页⾯会出现403
  1.在使⽤form类时,需要在form标签中第⼀⾏添加{% csrf_token %},⽤来在请求后添加⼀个csrf随机⽣成的字符串,防⽌表单出现重复提交。
  2.除了第⼀个⽅法,还可以在settings.py配置⽂件中 MIDDLEWARE 中将'django.middleware.csrf.CsrfViewMiddleware',注释掉,不使⽤crsf.
  templates-form.py代码
1 <form action="/add_article/" method="post">
2    {% csrf_token %}
3#django默认post请求crsf token为空,必须要在form中加⼊这⼀⾏;或者将settings.py
4#'django.middleware.csrf.CsrfViewMiddleware'这⼀⾏注释掉
5    title:<input type="text" name="title">
6    desc:<input type="text" name="desc">
7    content:<input type="text" name="content">
8  <!--category:<input type="text" name="category">-->
9    <select name="category" >
10        {% for a in categories %}
11        <option value="{{ a.id }}" >{{ a.name }}</option>
12        {% endfor %}
13    </select>
14    <input type="submit" value="提交">
  views.py
1from django.shortcuts import render,HttpResponseRedirect
2from .models import Category,Article
3from django.views import View
4
5# fvb⽅式
6def add_article(request):
hod=='GET':
8        categories = Category.objects.all()
9return render(request,'form.html',locals())
10else:
11        title = ('title')
12        desc = ('desc')
13        content = ('content')
14        category = ('category')
django怎么学15        article = Article(title=title,desc=desc,content=content,category=category)#新增数据
16        article.save()
17return HttpResponseRedirect('/index')#重定向到index.html
18
19
20# cvb⽅式,cvb会⾃动匹配⽅法,如果是get请求会⾃动调⽤get⽅法,是post⽅法⾃动调⽤post⽅法
21class ArticleView(View):
22def get(self,request):
23print('get请求.....')
24        categories = Category.objects.all()
25return render(request,'form.html',locals())
26
27def post(self,request):
28print('post请求')
29        title = ('title')
30        desc = ('desc')
31        content = ('content')
32        category = ('category')
33        article = Article(title=title,desc=desc,content=content,category=category)#新增数据
34        article.save()
35return HttpResponseRedirect('/index')#重定向到index.html
urls.py
ib import admin
2from django.urls import path
3from user.views import index,category,detail,add_article,ArticleView
4
5 urlpatterns = [
6    path('admin/', admin.site.urls),
7    path('index/', index),#第⼀个参数index 指的是页⾯的后缀地址,第⼆个参数index为view.py⽂件的⽅法名
8    path('',index),
9    path('category/<int:id>',category),#第⼀个参数中传参,第⼆个参数中为view.py⽂件的⽅法名
10    path('detail/',detail),
11    # path('add_article/',add_article) #cvb
12    path('add_article/',ArticleView.as_view()) #fvb
13 ]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。