cvb i.e. transmission get and post requests funtion view class view and in two ways
Wording not separated front and rear ends, define a html (form.html), the write logic (cvb & fvb) in the view
Note : Note csrf problems, if the data submitted will be reported repeated multiple times 403, two kinds of solutions
1. In the settings.py-MIDDLEWARE- CSRF (fourth row) commented
2. Write {% csrf_token%} in the form.html
form.html code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/add_article/" method="post">
{% csrf_token %}
title:<input type="text" name="title"> desc:<input type="text" name="desc"> content:<input type="text" name="content"> category:<select name="category"> {% for c in categorys %} <option value="{{ c.id }}">{{ c.name }}</option> {% endfor %} </select> <input type="submit" value="提交"> </form> </body> </html>
views.py code
#function fvb方式 def add_article(request): if request.method == 'GET': categorys = Category.objects.all() return render(request,'form.html',locals()) else: title = request.POST.get('title') desc = request.POST.get('desc') content = request.POST.get('content') category = request.POST.get('category') article = Article(title=title,desc=desc,category_id=category,content=content) article.save() return HttpResponseRedirect('/blog')#重定向 #class cvb方式 class ArticleView(View): def get(self,request): categorys = Category.objects.all() return render(request, 'form.html', locals()) def post(self,request): title = request.POST.get('title') desc = request.POST.get('desc') content = request.POST.get('content') category = request.POST.get('category') article = Article(title=title, desc=desc, category_id=category, content=content) article.save() return HttpResponseRedirect('/blog') # 重定向
urls.py
from django.contrib Import ADMIN from django.urls Import path from user.views Import index, Test, Blog, Detail, add_article, ArticleView the urlpatterns = [ path ( ' ADMIN / ' , admin.site.urls), path ( ' index / ' , index), # add access url, index / can be customized, index method views.py the path ( ' Test / ' , Test), path ( ' Blog / ' , Blog), # path (' category / <int: id> ', category), path('detail/', detail), # path('add_article/', add_article),#fvb方式 path('add_article/', ArticleView.as_view()),#cvb方式 ]