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
1 from django.shortcuts import render,HttpResponseRedirect
2 from .models import Category,Article
3 from django.views import View
4
5 # fvb方式
6 def add_article(request):
7 if request.method=='GET':
8 categories = Category.objects.all()
9 return render(request,'form.html',locals())
10 else:
11 title = request.POST.get('title')
12 desc = request.POST.get('desc')
13 content = request.POST.get('content')
14 category = request.POST.get('category')
15 article = Article(title=title,desc=desc,content=content,category=category)#新增数据
16 article.save()
17 return HttpResponseRedirect('/index')#重定向到index.html
18
19
20 # cvb方式,cvb会自动匹配方法,如果是get请求会自动调用get方法,是post方法自动调用post方法
21 class ArticleView(View):
22 def get(self,request):
23 print('get请求.....')
24 categories = Category.objects.all()
25 return render(request,'form.html',locals())
26
27 def post(self,request):
28 print('post请求')
29 title = request.POST.get('title')
30 desc = request.POST.get('desc')
31 content = request.POST.get('content')
32 category = request.POST.get('category')
33 article = Article(title=title,desc=desc,content=content,category=category)#新增数据
34 article.save()
35 return HttpResponseRedirect('/index')#重定向到index.html
urls.py
1 from django.contrib import admin
2 from django.urls import path
3 from 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 ]