Tips : When the article is finished , Directories can be generated automatically , How to generate it, please refer to the help document on the right
Django Form Component is used to initialize the page , Generate HTML label , In addition, you can also verify the data submitted by users ( Display error message ).
# TestDB Under folder app_example.py
from django import forms
from django.core.exceptions import ValidationError # Error checking
class MyForm(forms.Form):
# label Represents generated html Text description in front of input box
# error_messages Indicates an error message
name = forms.CharField(min_length=4, label=" full name ", error_messages={
"min_length": " The length cannot be less than 4", "required": " This field cannot be empty "})
age = forms.IntegerField(label=" Age ")
salary = forms.IntegerField(label=" Wages ")
r_salary = forms.IntegerField(label=" Confirm salary ")
# Use route distribution
# HelloDJango For project root urls.py
from django.urls import path, include
urlpatterns = [
# forms Components
path("testdb/", include("TestDB.urls")),
]
# TestDB Under folder urls.py
from django.urls import path
from TestDB import views
urlpatterns = [
# forms Components
path("add_info/", views.addInfo)
]
# TestDB Under the views.py
def addInfo(request):
# The direct send request is GET, Render the page
if request.method == "GET":
form = MyForm()
return render(request, "index.html", {
"form": form})
else:
# Processing form submission
form = MyForm(request.POST)
if form.is_valid(): # If the verification is successful
data = form.cleaned_data # The data that has been verified successfully is placed in cleaned_data in
print(data)
return HttpResponse(json.dumps(data, ensure_ascii=False), 'application/json')
else:
print(form.errors)
clean_errors = form.errors.get("__all__")
return render(request, "index.html", {
"form": form, "clean_errors": clean_errors})
<body>
<h1>Hello World</h1>
<form action="" method="post">
{% csrf_token %} <!-- Handle POST Submit -->
{
{ form.as_p }} <!-- Get form elements -->
<input type="submit" vlaue=" Submit "/>
</form>
</body>
Can pass clean_data Get the data after successful verification
If the verification fails, you can obj.errors Get error
You can perform error verification on fields through hooks , Use form Provided ValidationError, Import :
from django.core.exceptions import ValidationError
# Define local hook , With clean_ Field name Mode definition
def clean_name(self):
value = self.cleaned_data.get("name")
if value.isdigit():
raise forms.ValidationError(" User names cannot be pure numbers ")
else:
return value
def clean(self):
salary = self.cleaned_data.get("salary")
r_salary = self.cleaned_data.get("r_salary")
if salary == r_salary:
return self.cleaned_data
else:
raise ValidationError(" Please confirm that the salary is the same ")
Simple record implementation forms The flow of components