Example Project Project Requirement analysis
There are several features that can be achieved by Form forms:
1. Automatic generation of HTML tags
2. Retention of last input data
3. Verification of input data
Code Implementation Database Code
from django.db import modelsclass Classes(models.Model): title = models.CharField(max_length=32)class Student(models.Model): sname = models.CharField(max_length=32) email = models.CharField(max_length=32) age = models.IntegerField() cls = models.ForeignKey(‘Classes‘,on_delete=models.CASCADE)class Teacher(models.Model): tname = models.CharField(max_length=32) c2t = models.ManyToManyField(‘Classes‘)
Database error ' On_delete '
Djiango when found to execute mange.py makemigrations and migrate will be error, less position parameter on_delete, check a bit because the way to specify the foreign key is wrong, change it OK.
One-to-many design multi-party hold a foreign key
So the workaround is:
cls = models.ForeignKey(‘Classes‘)添加字段变成cls = models.ForeignKey(‘Classes‘,on_delete=models.CASCADE)
Class Management
Due to accidentally upgrade to the 2.0 version of Django, in the route to find that there is a problem, the following records. 2.0 is what we python3.x out for, first use to see
Class management function:
1. List of classes
2. Increase of class
3. Editing of the class
Routing URLs for classes
from django.contrib import adminfrom django.urls import path,re_pathfrom clsmanagent import viewsfrom django.conf.urls import urlurlpatterns = [ path(‘class_list/‘, views.class_list), path(‘add_class/‘, views.add_class), path(‘edit_class/<int:nid>/‘, views.edit_class),
Class management List
View File py
from django.shortcuts import render,redirect,HttpResponsefrom django.forms import Form, fields,widgetsfrom clsmanagent import models# 班级form验证class ClassForm(Form): title = fields.RegexField(‘全栈\d+‘,label=‘班级名称‘)# 班级信息def class_list(request): # if request.method == "GET": obj = models.Classes.objects.all() return render(request, ‘classlist.html‘, {‘obj‘: obj})
The HTML file for the class list
Class Add function
Adding feature View Files
#添加班级def add_class(request): if request.method == "GET": obj = ClassForm() return render(request,‘addclass.html‘,{‘obj‘:obj}) else: obj = ClassForm(request.POST) if obj.is_valid(): models.Classes.objects.create(**obj.cleaned_data) return redirect(‘/class_list/‘) return render(request, ‘addclass.html‘, {‘obj‘: obj})
Add the class HTML code
<form action="/add_class/" method="post"> {% csrf_token %} <p>{# {{ obj.as_p }}#} {{ obj.title }} {{ obj.errors.title.0 }} </p> <p> <input type="submit" value="提交"> </p></form>
Edit Class
Editing Class View Files
def edit_class(request,nid): if request.method == "GET": cls_info = models.Classes.objects.filter(id=nid).first() print(cls_info) obj = ClassForm(initial={‘title‘:cls_info.title}) return render(request,‘editclass.html‘,{‘obj‘:obj,‘nid‘:nid}) else: obj = ClassForm(request.POST) if obj.is_valid(): models.Classes.objects.filter(id=nid).update(**obj.cleaned_data) return redirect(‘/class_list/‘) return render(request,‘editclass.html‘,{‘obj‘:obj,‘nid‘:nid})
Edit the class's HTML code
<body>
Student table function
Functions and class functions, this puts all the view functions together
#学生列表def student_list (Request): Stu_list = models. Student.objects.all () return render (Request, ' studentlist.html ', {' stu_list ': Stu_list}) #添加学生 # #创建学生的Form条件验证class Stuform (Form): sname = fields. Charfield (min_length=2,max_length=6,label= ' student name ') email = fields. Emailfield () Age = fields. Integerfield () cls_id = fields. Integerfield (widget=widgets. Select (choices=models. Classes.objects.values_list (' id ', ' title ')) #把班级变成下拉框, here Django will automatically give us the value of the Select, do not need our own to worry about) def Add_stu (Request ): if Request.method = = "GET": obj = Stuform () return render (Request, ' addstudent.html ', {' obj ': obj}) el Se:obj = Stuform (Request. POST) if Obj.is_valid (): Models. Student.objects.create (**obj.cleaned_data) return redirect ('/student_list/') return render (request, ' adds Tudent.html ', {' obj ': obj}) #编辑学生def Edit_stu (Request,nid): if Request.method = = "GET": Row = models. Student.objects.filter (Id=nid). VALUES (' sname ', ' email ', ' age ', 'Cls_id '). First () #让他变成字典的类型可以传参到下面的form里面 because we know that the expression inside of data and initial is followed by a dictionary type, obj = Stuform (row) return render ( Request, ' editstudent.html ', {' obj ': obj, ' nid ': nid}) Else:obj = Stuform (Request. POST) if Obj.is_valid (): Models. Student.objects.filter (Id=nid). Update (**obj.cleaned_data) #参数我一个字典 return redirect ('/student_list/') retu RN render (Request, ' editstudent.html ', {' obj ': obj, ' nid ': nid})
Student List HTML code
Add Student HTML code
<form action="/add_stu/" method="post" novalidate> {% csrf_token %}
Edit Student HTML code
URLs failure
https://docs.djangoproject.com/en/2.0/intro/tutorial02/
django2.0 version of the main update urls,url into path, when using r‘^edit_class/(\d+)/‘, views.edit_class), routing, found that error 404 can not find the path. After viewing the document Discovery 2.0v version The URL becomes path, and the rule of path becomes the following:
<ul> {% for cls_list in obj %} <li>{{ cls_list.title }}<a href="/edit_class/{{ cls_list.id }}/">编辑</a></li> {% endfor %} </ul>
from django.urls import pathfrom . import viewsurlpatterns = [ path(‘edit_class/<int:nid>/‘, views.edit_class),]
This will change the incoming parameter to the specified, no need (\d+/),
Conversion format type
Description
Str
Match non-null characters except delimiter (/), default type <year> equivalent to <str:year>
Int
Match 0 and positive integers
Slug
A string that matches letters, numbers, bars, underscores, subsets of STR
Uuid
Matches a formatted UUID, such as 075194d3-6885-417e-a8a8-6c931e272f00
Path
Matches any non-empty string, including the path delimiter, which is the complete
Djagon Combat Form database and other operations