Use and Attention of forms Component in django
- 2021-07-10 20:13:06
- OfStack
forms component
The django framework provides an Form class to handle form submission data in web development.
Import related modules
from django import forms
from django.forms import fields
Regular use
class F1Form(forms.Form):
username = fields.CharField(max_length=18,min_length=2,required=True)
pwd = fields.CharField(required=True,max_length=16,min_length=6)
age = fields.IntegerField(required=True)
email = fields.EmailField(required=True)
Custom Error Message error_messages
class F1Form(forms.Form):
username = fields.CharField(max_length=18,
min_length=6,
required=True,
error_messages={
'required':' User name cannot be empty ',
'min_length':' User name too short ',
'max_length':' User name is too long '
}
)
Call of html
views section:
def rege(req):
obj = F1Form()
return render(req,'rege.html',{'OBJ':obj})
html section:
<form action="">
<p>{{ OBJ.username }}</p>
<p>{{ OBJ.pwd }}</p>
<p>{{ OBJ.age }}</p>
<p>{{ OBJ.email }}</p>
</form>
Background data validation:
obj = F1Form(req.POST)
if obj.is_valid(): # Determine whether the transmitted value has passed the verification
models.UserInfo.objects.create(**obj.cleaned_data) # Writing a value to the database
~ It should be noted that
create(**obj.cleaned_data)
Method to write to the database, is in forms submitted name name with the database only 1.
Summarize