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

Python introductory self-study advanced -web framework - 15. Djangos form verification 2

編輯:Python

Yes Form Do more in-depth research .

Use Form, need
1、 Create a template to validate user requests , It's a class :
from django import forms
class MyForm(forms.Form)
    user = forms.CharField(...)       # Default generation input type=‘text’
    email =  forms.EmailField(...)   # Default generation input type=‘email’
    pwd = forms.PasswordField(...) # Default generation input type=‘password’

Through this template , The front end can automatically generate the corresponding html label ,CharField(...) The default is to generate a input Of text Tags, etc. . Class is a template , There are several fields , Just verify a few fields

2、 There should be corresponding fields in the class :user = forms.CharField(...)

Field is inherited Field Class object , It is mainly used to verify the validity of the data of an input field , For example, the length can be defined in the parameter , This class mainly encapsulates some regular expressions .

When obj = MyForm(req.POST)
    obj.is_valid()     # This method is to loop through the validation rules for each field in the class , If there is 3 A field , If the validation result of a field is False, The results for False, All right , Only then True.

3、 plug-in unit :
For fields , Build on the front end HTML When labeling , If there is no other configuration , The default label will be generated , as CharField(...) The default is to generate a input Of text label . Can I change the default generated tag ? You can use plug-ins to change , Is to configure... In the parameters “widget=” Options . The following form

user = forms.CharField(...,widget=Input box ) 

about CharField class , The source code is as follows

  stay CharField There is no widget, In his father's class Field It defines widget=TextInput

For other field classes , as follows :

  Basically, the default is defined in this class widget.

django The list of field classes provided is as follows :

therefore , When defining different fields , It can be done by widget Modify different plug-ins to generate different tags ,fields.py These classes in are plug-ins .

Such as user = forms.CharField(widget=forms.PasswordField), The password input box is generated , Instead of the default text input box .

You can also add attributes to the generated tags :

user = forms.CharField(widget=forms.TextField(attrs={‘class’:‘c1’,‘placeholder’:‘ user name ’}))

test :

Template class :

from django import forms
class MyForm(forms.Form):
user = forms.CharField()
user1 = forms.CharField(widget=forms.PasswordInput)
user2 = forms.CharField(widget=forms.TextInput(attrs={'class':'cl1','placeholder':' user name '}))
user3 = forms.ChoiceField(choices=[(1,' football '),(2,' Basketball '),(3,' Volleyball '),(4,' Table Tennis ')])

The view function :

def detail(req):
obj = myviews.MyForm()
return render(req,'detail.html',{'obj':obj})

front end :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>user:{
{ obj.user }}</p>
<p>user1:{
{ obj.user1 }}</p>
<p>user2:{
{ obj.user2 }}</p>
<p>user3:{
{ obj.user3 }}</p>
</body>
</html>

result :

 

  The fields of the template also have the function of automatic type conversion , Such as :

user4 = forms.IntegerField(), The string passed from the front end , Here we are. , Will be automatically converted to an integer number .

  Parameters of fields :

Field
required=True, Whether a value must be entered , That is, it cannot be empty , default setting
widget=None, HTML plug-in unit
label=None, Used to generate Label Label or display content
initial=None, Initial value
help_text='', Help information ( Show... Next to the label )
error_messages=None, error message {'required': ' Can't be empty ', 'invalid': ' Format error '}
show_hidden_initial=False, Add a hidden plug-in with default value after the current plug-in ( It can be used to check whether two inputs are always )
validators=[], Custom validation rules
localize=False, Whether localization is supported or not
disabled=False, Can I edit
label_suffix=None Label Content suffix
CharField(Field)
max_length=None, Maximum length
min_length=None, Minimum length
strip=True Remove user input blanks
IntegerField(Field)
max_value=None, Maximum
min_value=None, minimum value
FloatField(IntegerField)
...
DecimalField(IntegerField)
max_value=None, Maximum
min_value=None, minimum value
max_digits=None, Total length
decimal_places=None, Decimal length
BaseTemporalField(Field)
input_formats=None Time format
DateField(BaseTemporalField) Format :2015-09-01
TimeField(BaseTemporalField) Format :11:12
DateTimeField(BaseTemporalField) Format :2015-09-01 11:12
DurationField(Field) The time interval :%d %H:%M:%S.%f
...
RegexField(CharField)
regex, Custom regular expressions
max_length=None, Maximum length
min_length=None, Minimum length
error_message=None, Ignore , Use of error messages error_messages={'invalid': '...'}
EmailField(CharField)
...
FileField(Field)
allow_empty_file=False Allow empty files
ImageField(FileField)
...
notes : need PIL modular ,pip3 install Pillow
When the above two dictionaries are used , Two things to note :
- form In the form enctype="multipart/form-data"
- view Function obj = MyForm(request.POST, request.FILES)
URLField(Field)
...
BooleanField(Field)
...
NullBooleanField(BooleanField)
...
ChoiceField(Field)
...
choices=(), Options , Such as :choices = ((0,' Shanghai '),(1,' Beijing '),)
required=True, If required
widget=None, plug-in unit , Default select plug-in unit
label=None, Label Content
initial=None, Initial value
help_text='', Help tips
ModelChoiceField(ChoiceField)
... django.forms.models.ModelChoiceField
queryset, # Query the data in the database
empty_label="---------", # The default empty display content
to_field_name=None, # HTML in value The field corresponding to the value of
limit_choices_to=None # ModelForm Chinese vs queryset Second screening
ModelMultipleChoiceField(ModelChoiceField)
... django.forms.models.ModelMultipleChoiceField
TypedChoiceField(ChoiceField)
coerce = lambda val: val Make a conversion of the selected value
empty_value= '' Default value of null value
MultipleChoiceField(ChoiceField)
...
TypedMultipleChoiceField(MultipleChoiceField)
coerce = lambda val: val One conversion for each selected value
empty_value= '' Default value of null value
ComboField(Field)
fields=() Use multiple validations , as follows : That is to verify the maximum length 20, Also verify the email format
fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
MultiValueField(Field)
PS: abstract class , Subclasses can aggregate multiple dictionaries to match a value , To cooperate MultiWidget Use
SplitDateTimeField(MultiValueField)
input_date_formats=None, Format list :['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
input_time_formats=None Format list :['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
FilePathField(ChoiceField) file option , The files in the directory are displayed on the page
path, Folder path
match=None, Regular matching
recursive=False, Recurse the folder below
allow_files=True, Allow files
allow_folders=False, Allow folders
required=True,
widget=None,
label=None,
initial=None,
help_text=''
GenericIPAddressField
protocol='both', both,ipv4,ipv6 Supported by IP Format
unpack_ipv4=False analysis ipv4 Address , If it is ::ffff:192.0.2.1 When , It can be interpreted as 192.0.2.1, PS:protocol It has to be for both To enable
SlugField(CharField) Numbers , Letter , Underline , minus sign ( A hyphen )
...
UUIDField(CharField) uuid type
...

test :

Back end :

from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from myadminzdy import models
from django import forms
from django.core.validators import RegexValidator
class MyForm(forms.Form):
# user = forms.CharField()
# user1 = forms.CharField(widget=forms.PasswordInput)
# user2 = forms.CharField(widget=forms.TextInput(attrs={'class':'cl1','placeholder':' user name '}))
# user3 = forms.ChoiceField(choices=[(1,' football '),(2,' Basketball '),(3,' Volleyball '),(4,' Table Tennis ')],)
f1 = forms.CharField() # The default field cannot be empty , namely required=True
f2 = forms.CharField(required=False) # Field can be empty
f3 = forms.CharField(label="f3 Of label") # The front end can be used .label、.id_for_label、.label_tag
f4 = forms.CharField(initial=' Initial value ') # The generated tag has an initial value
f5 = forms.CharField(initial=' Initial value 11111',show_hidden_initial=True) # In addition to generating a displayed label , Also generate a hidden tag , Its value remains the original value , It can be used for comparison of tag values
f6 =forms.CharField(validators=[RegexValidator(r'^[0-9]+$','jiaoyan1:quanshuzi'),RegexValidator(r'^135[0-9]+$','jiaoyan2:135kaishi')])
# Add custom verification rules , Use validators= Parameters , The rule is RegexValidator The object of , Add two here , Its two parameters , One is the rule , One is the error message
# Printed error messages :{"f6": [{"message": "jiaoyan1:quanshuzi", "code": "invalid"}, {"message": "jiaoyan2:135kaishi", "code": "invalid"}]}
f7 = forms.CharField(validators=[RegexValidator(r'^[0-9]+$', 'jiaoyan1:quanshuzi'),
RegexValidator(r'^135[0-9]+$', 'jiaoyan2:135kaishi')],
error_messages={'required':'111-buweikong','invalid':'222-geshicuowu'})
# test error_message Parameters
# {"f6": [{"message": "jiaoyan1:quanshuzi", "code": "invalid"}, {"message": "jiaoyan2:135kaishi", "code": "invalid"}],
# "f7": [{"message": "222-geshicuowu", "code": "invalid"}, {"message": "222-geshicuowu", "code": "invalid"}]}
# You can see , Set up error_message after , The last error message is in the form of error_message Set as the master
# about RegexValidator, You can also use the third parameter :code, To define different types , As in the system required、invalid etc.
f8 = forms.CharField(validators=[RegexValidator(r'^[0-9]+$', 'jiaoyan1:quanshuzi',code='f1'),
RegexValidator(r'^135[0-9]+$', 'jiaoyan2:135kaishi',code='f2')],
error_messages={'required':'111-buweikong','invalid':'222-geshicuowu'})
# {"f6": [{"message": "jiaoyan1:quanshuzi", "code": "invalid"}, {"message": "jiaoyan2:135kaishi", "code": "invalid"}],
# "f7": [{"message": "222-geshicuowu", "code": "invalid"}, {"message": "222-geshicuowu", "code": "invalid"}],
# "f8": [{"message": "jiaoyan1:quanshuzi", "code": "f1"}, {"message": "jiaoyan2:135kaishi", "code": "f2"}]}
# error_message High priority , according to code To cover , Want to modify the native error messages , You can set error_message.
f9 = forms.RegexField(r'^135[0-9]+$') # Custom regular expressions , Custom verification rule fields , The front end generates a text input box by default
f10 = forms.FileField() # Upload files , Generate input type by file The label of ,
# clean() Shown in :'f10': <InMemoryUploadedFile: 1.jpg (image/jpeg)>
f11 = forms.ImageField() # similar FileField, There are too many generated tags accept="image/*"
f12 = forms.ChoiceField(
choices=[(1,' badminton '),(2,' Table Tennis '),(3,' blue ball '),(4,' Volleyball ')],
initial=3
)
# The following selection boxes , The value is a string
f13 = forms.TypedChoiceField(
coerce=lambda x:int(x), # Type conversion
choices=[(1, ' badminton '), (2, ' Table Tennis '), (3, ' blue ball '), (4, ' Volleyball ')],
initial=3
)
#f12 and f13 Compare the results :'f12': '3', 'f13': 3, One is a string , One is integer
f14 = forms.MultipleChoiceField(
choices=[(1, ' badminton '), (2, ' Table Tennis '), (3, ' blue ball '), (4, ' Volleyball ')],
initial=[1,3]
)
# Checkbox , Note that the initial value is a list .
f15 = forms.FilePathField(path='myadminzdy/',allow_folders=True,allow_files=True,recursive=True)
# Drop down the selection box , The content is the file under the corresponding path
def detail(req):
if req.method == "GET":
obj = MyForm()
return render(req,'detail.html',{'obj':obj})
else:
obj = MyForm(req.POST,req.FILES)
# If you want to receive files , Add... To the parameter req.FILES, Because the uploaded file is saved in FILES Medium
obj.is_valid()
print(obj.clean())
print(obj.errors.as_json())
return render(req,'detail.html',{'obj':obj})

front end :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script src="/static/jquery-3.6.0.js"></script>
<script>
$('#id_f5').attr(value)
</script>
<body>
<form action="detail.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>f1:{
{ obj.f1 }}</p>
<p>f2:{
{ obj.f2 }}</p>
<!-- <p>{
{ obj.f3.label }}:{
{ obj.f3 }}</p> This kind of writing label is just a text -->
<!--<p>{
{ obj.f3.id_for_label }}{
{ obj.f3 }}</p> --> <!-- There's another property id_for_label, take id Value as label -->
<!-- <p><label for="{
{ obj.f3.id_for_label }}">{
{ obj.f3.label }}</label>{
{ obj.f3 }}</p>
This kind of writing , Click on the label , The focus enters the corresponding input box -->
{
{ obj.f3.label_tag }}{
{ obj.f3 }} <!-- The above method can be realized in this way -->
<p> Test the initial value {
{ obj.f4 }}</p>
<p> Test generate hidden tags {
{ obj.f5 }}</p>
<!-- <input type="text" name="f5" value=" Initial value 11111" id="id_f5">
<input type="hidden" name="initial-f5" value=" Initial value 11111" id="initial-id_f5">
-->
<p> Custom validation rules : {
{ obj.f6 }}</p>
<p> Custom validation rules : {
{ obj.f7 }}</p>
<p> Custom validation rules : {
{ obj.f8 }}</p>
<p> Custom validation rules : {
{ obj.f9 }}</p>
<p> Upload files : {
{ obj.f10 }}</p>
<p>tuoian Upload : {
{ obj.f11 }}</p>
<p> Drop down the selection box : {
{ obj.f12 }}</p>
<p> Drop down selection box type conversion : {
{ obj.f13 }}</p>
<p> Drop down multiple selection box : {
{ obj.f14 }}</p>
<p> Drop down the selection box - File list : {
{ obj.f15 }}</p>
<p><input type="submit" value=" Submit "></p>
</form>
</body>
</html>

django Provided widget plug-in unit :

TextInput(Input)
NumberInput(TextInput)
EmailInput(TextInput)
URLInput(TextInput)
PasswordInput(TextInput)
HiddenInput(TextInput)
Textarea(Widget)
DateInput(DateTimeBaseInput)
DateTimeInput(DateTimeBaseInput)
TimeInput(DateTimeBaseInput)
CheckboxInput
Select
NullBooleanSelect
SelectMultiple
RadioSelect
CheckboxSelectMultiple
FileInput
ClearableFileInput
MultipleHiddenInput
SplitDateTimeWidget
SplitHiddenDateTimeWidget
SelectDateWidget
# single radio, The value is a string
# user = fields.CharField(
# initial=2,
# widget=widgets.RadioSelect(choices=((1,' Shanghai '),(2,' Beijing '),))
# )
# single radio, The value is a string
# user = fields.ChoiceField(
# choices=((1, ' Shanghai '), (2, ' Beijing '),),
# initial=2,
# widget=widgets.RadioSelect
# )
# single select, The value is a string
# user = fields.CharField(
# initial=2,
# widget=widgets.Select(choices=((1,' Shanghai '),(2,' Beijing '),))
# )
# single select, The value is a string
# user = fields.ChoiceField(
# choices=((1, ' Shanghai '), (2, ' Beijing '),),
# initial=2,
# widget=widgets.Select
# )
# multi-select select, The value is a list
# user = fields.MultipleChoiceField(
# choices=((1,' Shanghai '),(2,' Beijing '),),
# initial=[1,],
# widget=widgets.SelectMultiple
# )
# single checkbox
# user = fields.CharField(
# widget=widgets.CheckboxInput()
# )
# multi-select checkbox, The value is a list
# user = fields.MultipleChoiceField(
# initial=[2, ],
# choices=((1, ' Shanghai '), (2, ' Beijing '),),
# widget=widgets.CheckboxSelectMultiple
# )

For fields , Mainly for verification , about widget plug-in unit , It mainly defines the label types generated by the front end , If the field defines CharField, The plug-in uses MultipleSelect, The front end returns a list , But validation is done by string , It loses the meaning of verification , So we should match the two .

Drop down radio box , Get data dynamically through the database :

page :

  Back end code :

# models In the code , Generate database
class UserType(models.Model):
caption = models.CharField(max_length=32)
# In the view function
# Define template classes
from myadminzdy import models
class MyFormDb(forms.Form):
host = forms.CharField()
host_type = forms.IntegerField(
# widget=forms.Select(choices=[(1,'BJ'),(2,'SH')]) # Static acquisition
# widget = forms.Select(choices=models.UserType.objects.all().values_list('id','caption'))
# Get data dynamically from the database ,django Get... At startup , Only once
widget=forms.Select(choices=[])
)
# In order to record changes in the database , The front end dynamically obtains the latest data , You need to perform a data acquisition every time the object is generated
def __init__(self,*args,**kwargs):
super(MyFormDb,self).__init__(*args,**kwargs)
self.fields['host_type'].widget.choices = models.UserType.objects.all().values_list('id','caption')
# Each instantiation will retrieve the database data and assign it to choices.
# The view function
def db(req):
if req.method == "GET":
obj = MyFormDb()
return render(req, 'db.html', {'obj': obj})
else:
obj = MyForm(req.POST, req.FILES)
# If you want to receive files , Add... To the parameter req.FILES, Because the uploaded file is saved in FILES Medium
obj.is_valid()
print(obj.clean())
print(obj.errors.as_json())
return render(req, 'db.html', {'obj': obj})

front end :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{
{ obj.host }}
{
{ obj.host_type }}
</body>
</html>

The key point is , When defining template classes , According to the previous writing , Define only fields , Set... When defining fields choices Get database data , When testing , When the background database changes , The front-end data has not changed , Because of the choices Value is executed only once when it is first loaded , In the future, it will be a copy of the loaded value , So we need to define __init__(), Query the database every time you instantiate , And assign it to choices, In this way, the data can be updated in real time .

Pay attention to this sentence :
self.fields['host_type'].widget.choices = models.UserType.objects.all().values_list('id','caption')

By this inference , There is a dictionary type field in the template class fields, We define the fields as key value pairs , So you can use fields['host_type'] Get forms.IntegerField(widget=forms.Select(choices=[])), This is another dictionary structure , Can pass .widget Get forms.Select(choices=[]), Another dictionary structure , stay .choices Get choices.

Define a user table :

class UserType(models.Model):
caption = models.CharField(max_length=32)
class User(models.Model):
username = models.CharField(max_length=32)
user_type = models.ForeignKey('UserType',on_delete=models.DO_NOTHING)

The foreground request is passed to a user id, Returns its user name and type :

def db(req):
if req.method == "GET":
nid = req.GET.get('nid')
m = models.User.objects.filter(id=nid).first()
dic = {'host':m.username,'host_type':m.user_type_id}
obj = MyFormDb(dic)
return render(req, 'db.html', {'obj': obj})

You only need to form a dictionary format data of the validation template class field , Here is the dic ={'host':'','host_type':''}, Just pass it to the generated template object .


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