In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is the knowledge related to Django Form components". In the daily operation, I believe that many people have doubts about the knowledge related to Django Form components. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is the knowledge related to Django Form components?" Next, please follow the editor to study!
Understanding of Form components
When not using Form components
In general, if we write the input box, it is usually written like this in Html.
Code
... User name: password:.
Realize the effect
When using Form components
When using Form components, we usually need to define Form classes.
This Form, the field inside, can be understood as the input tag, but it is written on the back end.
Form class
From django.forms import Form class LoginForm (Form): uname = fields.CharField (label= "username") upwd = fields.CharField (label= "password")
Views.py
From django.shortcuts import render def login (request): form = LoginForm () return render (request, "login_f.html", {"form": form})
Html
... {{form.uname.label}}: {{form.uname}} {{form.uname.errors.0}} {{form.upwd.label}}: {{form.upwd}} {{form.upwd.errors.0}}...
Small summary
You can find that I did not write input code, but directly called the back-end form. It came out.
Html generated by the Form class
You can find that it is basically similar to the Html written by yourself, and the generated id is id+.
Map of Html generated by Form and manually written Html
Determined by the corresponding graph, through the back-end form. What is generated directly is the input tag.
Well, at this point, we have determined that the Form class is the one that generates the input tag for us.
Form usage
There are the following steps to use.
1. Create a Form class that matches models as much as possible.
Class LoginForm (Form): uname = fields.CharField (label= "username") upwd = fields.CharField (label= "password")
Because the data submitted by Form can be converted to dict,key, which is the name of the Form field.
If the Form field matches the models, directly models..objects.create (* * dict).
two。 If it is a GET request, instantiate the Form object and return the page.
Def login (request): if request.method = 'GET': form = LoginForm () return render (request, "login_f.html", {"form": form})
3. In the case of a POST request, request.POST,request.FILES is passed in when the Form object is instantiated, and validated.
# and then elif request.method = = "POST": form = LoginForm (request.POST, request.FILES) # Verification data if form.is_valid (): # data after successful verification Key is the field name of the Form class print (form.cleaned_data) # {'uname':' 1212, 'upwd':' 1212'} return HttpResponse ("ok") # validation failed # although the page is returned # but form saves the contents of the last input box and displays the errors information return render (request "login_f.html", {"form": form})
4. The front end uses the form object passed from the back end.
Way one, click on each field
{{form.uname.label}}: {{form.uname}} {{form.uname.errors.0}} {{form.upwd.label}}: {{form.upwd}} {{form.upwd.errors.0}}
Method 2: loop the form object
The form object can be looped, and each form object of the loop is each field object.
{% for foo in form%} {{foo.label}: {{foo}} {{foo.errors.0}} {% endfor%}
So, if a table has a lot of fields, use a loop as much as possible.
Form field
The Form component mainly helps us to do verification, so, of course, there are many parameters such as:
No can be empty.
The content displayed by label.
Wait.
Common field
The field class is the base class for all fields
The Field parameters are as follows
Required=True, whether it is allowed to be empty. Default True, which cannot be empty.
Widget=None, plug-in, input details displayed
Label=None,label, the content displayed on the label
Help_text= "", help information (displayed next to the label)
Error_massages=None, error message {"required": "cannot be empty",...}
Show_hidden_initial=False, whether to add a hidden plug-in with default value after the current plug-in (can be used to verify whether the input is consistent twice)
Validators= [], custom validation rule function
Localize=False, whether localization is supported
Disabled=False, can you edit it?
Label_suffix=None,Label content suffix
CharField (Field), one of the more commonly used fields
Min_length=None, minimum length
Max_length=None, maximum length
Strip=True, whether to remove input blanks
IntegerField (Field)
Max_value=None, maximum
Min_value=None, minimum
DecimalField (IntegerField)
Max_value=None, maximum
Min_value=None, minimum
Max_digits=None, maximum length
Decimal_places=None, length of decimal places
Other fields include
BaseTemporalField (Field) DateField (BaseTemporalField) TimeField (BaseTemporalField) DateTimeField (BaseTemporalField) DurationField (Field) RegexField (CharField) EmailField (CharField) FileField (Field) ImageField (FileField) URLField (Field) BooleanField (Field) NullBooleanField
... There are still many fields, which I will not repeat here. For more information, please see the official website:
Https://docs.djangoproject.com/zh-hans/2.0/ref/forms/api/#django.forms.BoundField
Multiple selection field
ChoiceField (Field)... Choices= () # options, such as: choices= ((1) 'Class 1'), (2 'Class 2'),) required=True # whether the widget=None # plug-in is required Default select plug-in label=None # Label content initial=None # initial value help_text='' # help prompt from django.forms.models import ModelChoiceField # Radio ModelChoiceField (ChoiceField) queryset=None # query data in the database empty_label= "-" # default empty display content to_field_name=None # HTML corresponding to the value of the field limit_choices_to=None # ModelForm Queryset secondary screening # multiple from django.forms.models import ModelMultipleChoiceField ModelMultipleChoiceField (ModelChoiceField)...
Plug-in corresponding to widget parameter
Even if the field is CharField, the final effect is dominated by plug-ins!
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
Widget example
From django.forms import fields, widgets from django.forms import Form user = fields.CharField (initial=2, widget=widgets.RadioSelect (choices= (1m 'Class 1'), (('Class 2'),)) # or user = fields.ChoiceField (choices= ('Class 1'), ('Class 2'),), initial=2, widget=widgets.RadioSelect) # multiple select The value is the list user = fields.MultipleChoiceField (choices= ((1)), (2)), initial= [1,], widget=widgets.SelectMultiple) # get multiple choices from the database # from django.forms import Form from django.core.validators import RegexValidator class Form class (Form): user = fields.ChoiceField ((1) choices= ((1)), (2)), initial=2 Widget=widgets.Select) def _ _ init__ (self, * args, * * kwargs): super (MyForm,self). _ _ init__ (* args, * * kwargs) # self.fields ['user']. Widget.choices = ((1)' Class 1'), (2) "Class 2") ) # or self.fields ['user']. Widget.choices = models.Classes.objects.all (). Value_list (' id','caption') # method II from django.forms import models as form_model class Form class (Form): depart = form_model.ModelMultipleChoiceField (queryset=models.Depart.objects.all ()) so far The study of "what is the knowledge related to Django Form components" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.