程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Django] form component

編輯:Python

Tips : When the article is finished , Directories can be generated automatically , How to generate it, please refer to the help document on the right

List of articles

  • Form Components use
  • Local hook and global hook
  • summary


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 ).

Form Components use

  1. establish Fom Component class
# 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 ")
  1. Define routes
# 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)
]
  1. Define processing functions
# 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})
  1. html page
<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>
  1. Running results

Can pass clean_data Get the data after successful verification
If the verification fails, you can obj.errors Get error

Local hook and global hook

You can perform error verification on fields through hooks , Use form Provided ValidationError, Import :

from django.core.exceptions import ValidationError
  • Definition of hook : Local hook -》 clean_ Field name , Such as
 # 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
  • global hook
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 ")

summary

Simple record implementation forms The flow of components


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved