The following describes how the forms module interacts with the background database, writing data from the from submission to the background database.
Froms in combination with model
1. Create data table in Vim modes.py
From django.db import Models
Class Admin (model. Model):
Gender_tuple= (
(1, ' Male '),
(2, ' Women '),
)
Username = models. CharField (max_length=50)
email = models. Charfield (MAX_LENGTH=50)
Gender = models. Charfield (Max_length=50,choices=gender_tuple)
#choices =gender_tuple A Select method in pretty HTML
Vim forms.py
From Django Import forms
From APP01 import Models
Class Adminmodelform (forms. Modelform):
Thinking: How to make modelfrom and form establish a relationship
Class Meta:
Model = Models.admin #models里的admin表
Fields = (' username ', ' email ') #在html页面指定显示的input字段
Customizing Plug-in Properties
Widgets = {
' Email ': forms. Passwordiput ((attrs={' class ': ' Auto '}),
}
2 Configuring database connection information in setting.py
DATABASES = {
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ',
' NAME ': ' CMDB ',
' USER ': ' Root ',
' PASSWORD ': ' tom123 ',
' HOST ': ',
' PORT ': ',
}
}
3 Initializing the database
Python mange.py makemigrations
Python mange.py syncdb
4.
Views.py write a method for generating the input tag of the forms module
def index3 (Request):
if Request.method = = ' Post ': #判断在html表单里面提交的方式是什么 (typically 2 ways POST and get)
form = forms. Adminmodelform (Request. POST)
Adminform is a class within the froms.py that is invoked through the forms method and assigned to the form
If Forms.is_valid (): #判断是否合法, the error message will be indicated on the front page of the wrong input
data = Form.cleaned_data request is accepted by the
Form.save () #表示直接讲数据存到数据库中
else: #如果输入规则不匹配在前台显示错误信息
Print Form.erros.as_data ()
Print Form.erros.as_json ()
Print Form.erros.as_text ()
Print Form.erros.as_ul ()
Common error message Formats
Else
form = forms. Adminmodelform () #判断如果不是post方法提交的
Print Fors.fields
return render_to_response (' index3.html ', {' Model ': form})
#把结果返回给前端的index2. Html,model is a variable inside the front index2.html that accepts data returned in the background, and the form is the real data
5.
<meta http-equiv= "Content-type" content= "text/html"/>
<title></title>
<body>
<form action= '/index3/' method= ' POST ' >
{{model.as_table}} has been shown in table Form
{{Model.as_ul}} has been shown in UL form
Detailed view of the form in the parent class---source code
Benefits Save Code
Bad style is not controllable
<input type= ' Submit ' value= ' submission '/>
</form>
</body>
6. Do not forget to configure the URL, that is, add a URL in urls.py point
Django Froms is used in conjunction with models