title: Django - form processing
copyright: true
top: 0
date: 2019-07-08 21:56:35
tags:
categories: WEB backend framework
permalink:
password:
keywords:
description: it's very considerate to use Django to process the form content
The world seems to be covered with a layer of white fog. I can't see the world clearly and I can't see myself. I just feel that I'm still stepping on solid land, which proves that I'm still alive and have nothing but myself.
Use form
Before submitting form content data, a form was written in HTML and then sent to the back end for processing.
But it becomes simple and clear in Django. First, create a new forms in the application directory py
# NHDZ/app/forms.py # coding:utf-8 from django import forms import datetime class Login(forms.Form): username = forms.CharField(label='user name', widget=forms.TextInput, initial='admin', label_suffix=':x:',required=True) # Here, the data transmitted from the form is set, and the form is automatically generated at the front end # The prefix of the label form displays' user name: ' # The widget type is text # The default value in the initial input box is admin # label_suffix: the default is user name. Now it is user name: x: # Required add a required attribute to the field and cannot be left blank. password = forms.CharField(label='password', widget=forms.PasswordInput, initial=datetime.date.today(),help_text='Enter your password here') # The default value of initial can get the date dynamically # help_ Texthelp document
Then you can write the functions of the login part in the view
# NHDZ/app/login.py # coding:utf-8 from .froms import Login from django.shortcuts import render from django.http import HttpResponse def index(request): # Landing page login_form = Login() # Instantiate the form, and then get the content of the form and render it to the html page return render(request, 'login.html', {'login_form': login_form}) def login(request): # Login verification if request.method == 'POST': do_login = Login(request.POST) # Instantiate the passed data if do_login.is_valid(): # Judge whether the data is legal username = do_login.cleaned_data['username'] # Cleared here_ The data method can clean the data and then obtain the data passowrd = do_login.cleaned_data['password'] return HttpResponse(username + '<br>' + passowrd)
Then create a new login in the templates folder HTML file, as follows
<form action="{%url 'login_success'%}" , method='POST'> {% csrf_token %} {{login_form}} <button type="submit">land</button> </form>
Finally, modify some routing files URLs py
# NHDZ/app/urls.py from django.urls import path from .views import Index,Add_Images,Add_Texts from .show import show from .login import index,login urlpatterns = [ path('',Index,name='index'), path('add_texts/',Add_Texts,name='add_texts'), path('add_images/',Add_Images,name='add_images'), path('show/<str:user>',show,name='show'), path('login/',index,name='login'), path('login_success/',login,name='login_success') ]
At this time, the adding function is almost completed. Visit to see if the form is generated
Click login to return the result
Automatic rendering format
In the demo login In HTML, I just pass in {{login_form}} to automatically generate the form, but the style is still very simple. Here, it can be beautiful by using the style sheet provided by Django
- {{form.as_table}} renders the form as a table element, with each input box as a label
- {{form.as_p}} wrap each input box of the form in a
tags in tag
- {{form.as_ul}} renders the form as a list element, with each input box as a
- label
Note: you have to write it yourself
and- label.
For example, I now put login Change the HTML file to this
<form action="{%url 'login_success'%}" , method='POST'> {% csrf_token %} {{login_form.as_p}} <button type="submit">land</button>
Now the style of the table displayed in the front end becomes maozi
Manual rendering format
When you want to reference bootstrap, you need to manually render the style sheet of each place. You can get the contents of the table in the following ways, and then render it
Use direct access
You can use forms Property to get the content of the form
<form action="{%url 'login_success'%}" , method='POST'> {% csrf_token %} <p>user id:{{ login_form.username }}</p> # Login here_ form. Username gets the data directly from the form, and then can add its own style <h2>password:{{login_form.password}} <button type="submit">land</button>
Obtain by overlapping representation
Iterate over the incoming data
<form action="{%url 'login_success'%}" , method='POST'> {% csrf_token %} {% for field in login_form %} # Here we iterate over the incoming form <p>{{ field.label_tag }}:{{ field }} # Field is the input content of the form, field label_ Tag is the style sheet of the form # Then use the p tag to render. Of course, you can replace the css style with the p tag </p> {{ field.errors }} # If the form is wrong, the error content will be prompted {% endfor %} <button type="submit">land</button>
Render form error message
Handle error messages in the form. For the error of each form field, it will actually generate an unordered list. Refer to the following:
<ul class="errorlist"> <li>Sender is required.</li> </ul>
This list has a default CSS style class errorlist. If you want to further customize this style, you can cycle the contents in the error list and set the style separately:
{% if login_form.errors %} <ol> {% for error in form.username.errors %} <li><strong>{{ error|escape }}</strong></li> {% endfor %} </ol> {% endif %}
All non field error messages, such as form errors and hidden field errors, are saved in {{form.non_field_errors}}. In the above example, we put it on the periphery of the form, and it will be rendered in the following HTML and CSS formats:
<ul class="errorlist nonfield"> <li>Generic validation error</li> </ul>
Using CSS style sheets
To sum up, you can set cascading style sheets in three ways (in the final analysis, two)
Back end processing
Write forms in Django Py form model, you can set the style by setting the properties of the Field class, such as
class Login(forms.Form): username = forms.CharField(label='user name', widget=forms.TextInput(attrs={'size': '20'})) # The representative size is 20px
Then, in the login. Of templates HTML modified to
<form action="{%url 'login_success'%}" , method='POST'> {% csrf_token %} {{login_form}} <button type="submit">land</button>
give the result as follows
Using front-end processing
As in the manual rendering format above, use field XXX gets the properties of the form, and then writes css in the front-end html
It should be noted that if you manually obtain the content data of the form at the front end, and then write css by yourself, the style set in the back-end code will not work
Semi automatic processing
The front-end framework is used to bootstrap. After practice, I found that the properties of bootstrap can be set through the front and back ends. In order to save trouble, I didn't save the bootstrap file in the static folder, so I directly referenced it
The backend code is as follows:
class Login(forms.Form): username = forms.CharField(label='user name', widget=forms.TextInput(attrs={'class': 'form-control'})) # Class: form control is a style of the input box of the bootstrap
The front-end code is as follows:
<head> <meta charset="UTF-8"> <title>land</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> # Through this, bootstrap is referenced directly and remotely </head> <body> <form action="{%url 'login_success'%}" , method='POST'> {% csrf_token %} <div class="col-md-3"> # Here is a fence style belonging to bootstrap {{login_form}} <button type="submit">land</button> </form> </div>
Results returned:
Familiar interface~
Upload file
Go FORMS
First, write a form model, which must contain a FileField:
# forms.py from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField()
The view that handles this form will be in request If you receive file data in files, you can use request Files ['file'] to obtain the specific data of the uploaded file. The key value 'file' is based on file = forms From the variable name of filefield().
Note: request Files is valid only when the request method is POST and the submitted request has the attribute enctype = "multipart / form data". Otherwise, request Files will be empty.
The following is an example of a view for receiving uploaded files:
# views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm # In addition, write a method to process the uploaded files and import them here from somewhere import handle_uploaded_file def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) # Pay attention to the way to obtain data if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form})
Note that the request Files is passed to the constructor of the form.
form = UploadFileForm(request.POST, request.FILES)
The following is a reference example of how to handle uploaded files:
def handle_uploaded_file(f): with open('some/file/name.txt', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk)
Traverse uploadedfile Chunks (), instead of using the read() method directly, can ensure that large files do not occupy too much memory of the system.
Go to MODELS
If the saving method of uploaded files is specified through the model of the model layer, it is more convenient to use ModelForm. Call form When saving (), the file object will be saved in the upload of the corresponding FileField_ Where specified by the to parameter.
from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import ModelFormWithFileField def upload_file(request): if request.method == 'POST': form = ModelFormWithFileField(request.POST, request.FILES) if form.is_valid(): # Just do this, and the file will be saved in the Model and uploaded_ The location specified by the to parameter form.save() return HttpResponseRedirect('/success/url/') else: form = ModelFormWithFileField() return render(request, 'upload.html', {'form': form})
If you construct an object manually, you can also simply transfer the file object directly from request Files is assigned to the model:
from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm from .models import ModelWithFileField def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): instance = ModelWithFileField(file_field=request.FILES['file']) instance.save() return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form})
Common properties of front-end form
attribute explain {{ login_form.label }} Field corresponding label information {{ login_form.label_tag }} Automatically generated fields label Label, note and{{ login_form.label }}The difference between. {{ login_form.id_for_label }} Custom field labels id {{ login_form.value }} The value of the current field, such as a Email The value of the field someone@example.com {{ login_form.html_name }} Specifies the generated by the field input In label name The value of the property {{ login_form.help_text }} Help information for field {{ login_form.errors }} Element containing error information {{ login_form.is_hidden }} Used to determine whether the current field is hidden. If yes, return True {{ login_form.field }} Returns a list of parameters for the field. for example{{ char_field.field.max_length }}
Field class built in the form
Reprint address, intrusion and deletion URL
For each field class, introduce its default widget, the value returned when the input is empty, and the verification method‘ Normalized to 'indicates which object is converted to PYthon. The available error information key indicates that the field can customize the type of error information (the key of the dictionary).
1. BooleanField
default Widget: CheckboxInput Null value: False Normalized as: Python of True perhaps False Available error message keys: required
##2. CharField
default Widget: TextInput Null value: and empty_value Any value given. Normalized to: one Unicode Object. verification max_length or min_length,If these two parameters are set. Otherwise, all inputs are legal. Available error message keys: min_length, max_length, required There are four optional parameters: max_length,min_length: Sets the maximum and minimum length of the string. strip: If True(Default), removing leading and trailing spaces from input. empty_value: The value used to represent "null". The default is an empty string.
##3. ChoiceField
Default Widget: Select
Null value: '' (an empty string)
Normalized to: a Unicode object.
Verify that the given value is in the list of options.
Available error message keys: required, invalid_choice
Parameter choices: used as an iteratable object (for example, list or tuple) or a callable object composed of a binary of the field options. The format is the same as the choices parameter for and ORM model fields.
##4. TypedChoiceField
Like ChoiceField, there are only two additional parameters: coerce and empty_value.
default Widget: Select Null value: empty_value The value of the parameter setting. Normalized as: coerce The value of the parameter type. Verify that the given value exists in the option list and can be cast. Keys for available error messages: required, invalid_choice
##5. DateField
Default Widget: DateInput
Null value: None
Normalized to: datetime Date object.
Verify that the given value is a datetime date,datetime.datetime or a string specifying the date format.
Key of error message: required, invalid
Receive an optional parameter: input_formats. A formatted list for converting strings to datetime Date object.
If not provided input_formats,The default input format is: ['%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y'] # '10/25/06' In addition, if you specify USE_L10N=False,The following formats will also be included in the default input format: ['%b %d %Y', # 'Oct 25 2006' '%b %d, %Y', # 'Oct 25, 2006' '%d %b %Y', # '25 Oct 2006' '%d %b, %Y', # '25 Oct, 2006' '%B %d %Y', # 'October 25 2006' '%B %d, %Y', # 'October 25, 2006' '%d %B %Y', # '25 October 2006' '%d %B, %Y'] # '25 October, 2006'
##6. DateTimeField
Default Widget: DateTimeInput
Null value: None
Normalized to: datetime. In Python Datetime object.
Verify that the given value is a datetime datetime,datetime.date or a string specifying the date format.
Key of error message: required, invalid
Receive an optional parameter: input_formats
If not provided input_formats,The default input format is: ['%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y'] # '10/25/06'
7. DecimalField
default Widget: When Field.localize yes False Shi Wei NumberInput,Otherwise TextInput. Null value: None Normalized as: Python decimal Object. Verify that the given value is a decimal number. Ignore leading and trailing whitespace. Key for error message: max_whole_digits, max_digits, max_decimal_places,max_value, invalid, required,min_value Receive four optional parameters: max_value,min_value:The range of allowed values needs to be assigned decimal.Decimal Object cannot be directly given an integer type. max_digits: The maximum number of digits allowed for the value (the total number of digits before and after the decimal point, and the leading zero will be deleted). decimal_places: The maximum number of decimal places allowed.
##8. DurationField
Default Widget: TextInput
Null value: None
Normalized to: Python timedelta.
Verify that the given value is a string and can be converted to a timedelta object.
Key of error message: required, invalid
9. EmailField
Default Widget: EmailInput
Null value: '' (an empty string)
Normalize to: Unicode object.
Use regular expressions to verify that the given value is a valid email address.
Key of error message: required, invalid
Two optional parameters are used for verification, max_length and min_length.
##10. FileField
The default Widget is ClearableFileInput
Null value: None
Normalized as: an UploadedFile object, which encapsulates the file content and file name into an object.
Verify that non empty file data has been bound to the form.
Key of error message: missing, invalid, required, empty, max_length
There are two optional parameters for validation: max_length and allow_empty_file.
##11. FilePathField
Default Widget: Select
Null value: None
Normalize to: Unicode object.
Verify that the selected option exists in the option list.
Key of error message: required, invalid_choice
This field allows you to select files from a specific directory. It has five additional parameters, of which path is required:
path: The absolute path of the directory to list. This directory must exist. recursive: If yes False(Default), only directly in path Select a file or directory under as an option. If yes True,This directory will be accessed recursively, and all subdirectories and files in it will be used as options. match: Regular expression pattern; Only file names that match this expression are allowed as options. allow_files: Optional. Default to True. Indicates whether files in the specified location should be included. It and allow_folders One must be True. allow_folders Optional. Default to False. Indicates whether the directory at the specified location should be included.
##12. FloatField
Default Widget: when field NumberInput when localize is False, TextInput otherwise.
Null value: None
Normalize to: Float object.
Verify that the given value is a floating point number.
Error message key: max_value, invalid, required, min_value
Receive two optional parameters for verification, max_value and min_value, which controls the range of allowed values.
##13. ImageField
The default Widget is ClearableFileInput
Null value: None
Normalized as: an UploadedFile object, which encapsulates the file content and file name as a separate object.
Verify that the file data is bound to the form and that the file is an image format that pilot can parse.
Key of error message: missing, invalid, required, empty, invalid_image
Using ImageField requires the installation of pilot (PIP install pilot). If you encounter an image corruption error when uploading an image, it usually means that a format not supported by pilot is used.
##14. IntegerField
Default Widget: when field NumberInput when localize is False, TextInput otherwise.
Null value: None
Normalized to: Python integer or long integer.
Verify that the given value is an integer. Leading and trailing spaces are allowed, similar to Python's int() function.
Error message key: max_value, invalid, required, min_value
Two optional parameters: max_value and min_value, which controls the range of allowed values.
##15. GenericIPAddressField
A field containing an IPv4 or IPv6 address.
default Widget: TextInput Null value:''((an empty string) Normalized to: one Unicode Object. Verify that the given value is valid IP Address. Key for error message: required, invalid There are two optional parameters: protocol and unpack_ipv4
##16. MultipleChoiceField
Default Widget: SelectMultiple
Null value: [] (an empty list)
Normalized to: a list of Unicode objects.
Verify that each value in the given value list exists in the selection list.
Key of error message: invalid_list, invalid_choice, required
##17. TypedMultipleChoiceField
Similar to MultipleChoiceField, it requires two additional parameters, coerce and empty_value.
default Widget: SelectMultiple Null value: empty_value Normalized as: coerce Parameter provides a list of type values. Verify that the given value exists in the option list and can be enforced. Key for error message: required, invalid_choice
##18. NullBooleanField
Default Widget: nullboolean select
Null value: None
Normalize to: Python None, False or True value.
Nothing is validated (that is, it never raises a ValidationError).
##19.RegexField
Default Widget: TextInput
Null value: '' (an empty string)
Normalized to: a Unicode object.
Verify that the given value matches a regular expression.
Key of error message: required, invalid
A required parameter is required: regex, which requires a matching regular expression.
Can also receive max_length,min_length and strip Parameters, similar CharField.
##20. SlugField
Default Widget: TextInput
Null value: '' (an empty string)
Normalized to: a Unicode object.
Verify that the given string contains only letters, numbers, underscores, and hyphens.
Key of error message: required, invalid
This field is used to represent the SlugField of the model in the form.
##21. TimeField
Default Widget: TextInput
Null value: None
Normalized to: a Python datetime Time object.
Verify that the given value is datetime Time or a string formatted in a specific time format.
Key of error message: required, invalid
Receive an optional parameter: input_formats, which attempts to convert a string to a valid datetime A list of formats for the time object.
If not provided input_formats,The default input format is: '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30'
##22. URLField
Default Widget: URLInput
Null value: '' (an empty string)
Normalized to: a Unicode object.
Verify that the given value is a valid URL.
Key of error message: required, invalid
Optional parameter: max_length and min_length
##23. UUIDField
Default Widget: TextInput
Null value: '' (an empty string)
Normalized to: UUID object.
Key of error message: required, invalid
##24. ComboField
Default Widget: TextInput
Null value: '' (an empty string)
Normalize to: Unicode object.
Verify the given value against each field of the parameter specified as ComboField.
Key of error message: required, invalid
Receive an additional required parameter: fields, a list of fields used to verify field values (in the order they are provided).
>>> from django.forms import ComboField >>> f = ComboField(fields=[CharField(max_length=20), EmailField()]) >>> f.clean('test@example.com') 'test@example.com' >>> f.clean('longemailaddress@example.com') Traceback (most recent call last): ... ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
##25. MultiValueField
Default Widget: TextInput
Null value: '' (an empty string)
Normalized to: the type returned by the compress method of the subclass.
Validates the given value against each field of the parameter specified as MultiValueField.
Key of error message: incomplete, invalid, required
##26. SplitDateTimeField
Default Widget: SplitDateTimeWidget
Null value: None
Normalized to: Python datetime Datetime object.
Verify that the given value is datetime Datetime or a string formatted in a specific datetime format.
Key of error message: invalid_date, invalid, required, invalid_time
Welcome to the official account: security research and development, get more related tools, courses and data sharing.