current position:Home>Django form
Django form
2022-06-24 08:58:26【My talented girlfriend】
Django To ensure the correct display of the form, you need to add CSRF( It is a protection method to prevent cross site requests from being forged and opened by default ), stay <form></form> Add... Between
{% csrf_token %}
In the project settings.py in * ‘django.middleware.csrf.CsrfViewMiddleware’, * introduce , Without this middleware , Manually add .
Upload files
First open path is GET request , If you click upload, it is POST request , If the file content is not empty , Then upload the file , The upload path is... Under the main project media/uploads/, If the path does not exist, create a new .open(os.path.join(path + myFile.name), ‘wb+’) Binary read / write opens the corresponding file ,chunks() Read and write files in blocks .
def upload_file(request):
if request.method == "GET":
return render(request, 'app1/upload.html')
if request.method == "POST":
myFile = request.FILES.get("myfile", None)
if myFile:
path = 'media/uploads/'
if not os.path.exists(path):
os.makedirs(path)
dest = open(os.path.join(path + myFile.name), 'wb+')
for chunk in myFile.chunks():
dest.write(chunk)
dest.close()
return HttpResponse(" Upload to complete ")
else:
return HttpResponse(" No files uploaded ")
Add route .
The file has been uploaded successfully .
Form Forms
Create a new one as follows form.py Write the following code
from django import forms
class UserInfoForm(forms.Form):
''' User state '''
STATUS = ((None, ' Please select '), (0, ' normal '), (1, ' Invalid '),)
username = forms.CharField(label=" User name ", min_length=6, widget=forms.widgets.TextInput(
attrs={
'class': 'form-control', 'placeholder': ' Please enter the user name '}
))
password = forms.CharField(label=" password ", min_length=6, max_length=10, widget=forms.widgets.PasswordInput(
attrs={
'class': 'password'}, render_value=True
))
age = forms.IntegerField(label=" Age ", initial=1)
mobile = forms.IntegerField(label=" Phone number ")
status = forms.ChoiceField(label=" User state ", choices=STATUS)
createdate = forms.DateTimeField(label=" Creation time ", required=False)
form field
form field | explain |
---|---|
CharField | Text input |
InterField/FloatField/DecimalField | Value input |
ChoiceField | Select the input box choices Specify the drop-down list |
FileField | file |
BooleanField | Check box |
DateField/DateTimeField/TimeField/ Time input box , Input format can be set input_format=[“%Y-%m-%d %H:%M”] | |
EmailField | Mail input box |
URLField | Road strength input box |
ModelChoiceField | Get the drop-down list from the database |
Field parameters
Field | explain |
---|---|
label | label label |
label_suffix | Label Label uniform suffix information |
initial | Initial value |
help_text | Field description information |
error_messages | Field description information |
validators | Validation rule |
required | Whether must |
disabled | Whether the field is editable |
widget | Appoint HTML style |
widget Parameters
Parameters | explain |
---|---|
PasswordInput | Password input box |
HiddenInput | Hidden elements |
Textarea | Text domain |
CheckboxInput | Check box |
FileInput | File input box |
RadioSelect | Radio button |
DateTimeInput | Time input box |
Select | The drop-down list |
SelectMuitiple | Checkbox |
Configure the view and path to display the corresponding form
app1 Under the views.py
def userinfo_form(request):
if request.method == "GET":
myForm = UserInfoForm()
return render(request, 'app1/userinfo.html', {
'form_obj': myForm})
userinfo.html
<html>
<head></head>
<body>
<form action="" method="POST">
{% csrf_token %} {
{ form_obj.as_p }}
<input type="submit" value=" Submit " />
</form>
</body>
</html>
- as_p Provide... For the form <p> label
- as_table Provide... For the form <table> label
- as_ui Provide... For the form <ui> label
The above uses as_p, So the source code shows p label .
Form validation
- is_valid() Verify that the form data is legal
- cleaned_data Get the data that the form has passed the validation
- errors Error message of form validation
stay form Add the following code to
class UserInfoForm__Msg(forms.Form):
''' User state '''
STATUS = ((None, ' Please select '), (0, ' normal '), (1, ' Invalid '),)
username = forms.CharField(label=" User name ", min_length=6, widget=forms.widgets.TextInput(
attrs={
'class': 'form-control', 'placeholder': ' Please enter the user name '}
), error_messages={
'required': ' User name cannot be empty ', 'min_length': ' Length not less than 6 position ', 'invalid': ' Can't contain special characters '
})
password = forms.CharField(label=" password ", min_length=6, max_length=10, widget=forms.widgets.PasswordInput(
attrs={
'class': 'password'}, render_value=True
), error_messages={
'required': ' The password cannot be empty ', 'min_length': ' The password cannot be less than 6 position ', 'max_length': ' The password cannot be redundant 10 position ',
})
age = forms.IntegerField(label=" Age ", initial=1, validators=[age_validate], error_messages={
'required': ' Age cannot be empty ',
})
mobile = forms.IntegerField(label=" Phone number ", validators=[mobile_validate], error_messages={
'required': ' Mobile number cannot be empty ',
})
status = forms.ChoiceField(label=" User state ", choices=STATUS, error_messages={
'required': ' User status cannot be empty ',
})
createdate = forms.DateTimeField(label=" Creation time ", required=False)
- required Error message when empty
- invalid Format validation error message
- min_length and max_length Error message that the length is not within the set range
Add view
def userinfo_form_msg(request):
if request.method == "GET":
myForm = UserInfoForm__Msg()
return render(request, 'app1/userinfoform.html', {
'form_obj': myForm})
else:
f = UserInfoForm__Msg(request.POST)
if f.is_valid():
print(f.cleaned_data['username'])
else:
errors = f.errors
print(errors)
return render(request, 'app1/userinfoform.html', {
'form_obj': f, 'errors': errors})
return render(request, 'app1/userinfoform.html', {
'form_obj': f})
Template file
<form action="" method="POST" novalidate>
{% csrf_token %}
<p>
{
{ form_obj.username.label }}:{
{ form_obj.username }} {
{ errors.username.0 }}
</p>
<p>{
{ form_obj.password}}{
{ errors.password.0 }}</p>
<p>{
{ form_obj.status.label }}:{
{ form_obj.status }} {
{ errors.status.0 }}</p>
<p>{
{ form_obj.age.label }}:{
{ form_obj.age }} {
{ errors.age.0 }}</p>
<p>{
{ form_obj.mobile.label }}:{
{ form_obj.mobile }} {
{ errors.mobile.0 }}</p>
Error message summary : {
{ errors }}
<input type="submit" value=" Submit " />
</form>
The self format verification of the form is also added here , Get data for the form
- f.clean() Get all the data
- f.clean_date[] Get the data of the corresponding value
- f.data Get all the data
Form model file upload example
Template file :upload_form.html
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %} {
{ form_obj.as_p }}
<br />
<input type="submit" value=" Upload files " />
<img src="media/uploads/{
{ user.heading }}"
</form>
Model file
stay models.py Add model to , If there is no primary key, it will be generated by default id Primary key of
class ImgFile(models.Model):
name = models.CharField(verbose_name=' User name ', max_length=300, default="")
heading = models.FileField(verbose_name=' file name ', upload_to='media/uploads/')
def __str__(self):
return self.name
class Meta:
verbose_name = ' User avatar information '
db_table = 'user_img'
Form model form.py
class ImgFileForm(forms.Form):
name = forms.CharField()
heading = forms.FileField()
Model view
If you upload a file , Save the file in the corresponding directory , And return the information of the file .
def ingfileform(request):
if request.method == "GET":
f = ImgFileForm()
return render(request, 'app1/upload_form.html', {
'form_obj': f})
else:
f = ImgFileForm(request.POST, request.FILES)
if f.is_valid():
name = f.cleaned_data['name']
heading = f.cleaned_data['heading']
path = 'media/uploads/'
if not os.path.exists(path):
os.makedirs(path)
dest = open(os.path.join(path + heading.name), 'wb+')
for chunk in heading.chunks():
dest.write(chunk)
dest.close()
userimg = ImgFile()
userimg.name = name
userimg.heading = heading
userimg.save()
print(' Upload successful ')
return render(request, 'app1/upload_form.html', {
'form_obj': f, 'user': userimg})
else:
print(f.errors)
route
re_path It is configured that the corresponding files can be accessed directly in the browser ,
from django.urls import path, include, re_path
from django.views.static import serve
from mywed import settings
path('app1/userimg/', views.ingfileform),
re_path('media/uploads/(?P<path>.*)', serve,
{
"document_root": settings.MEDIA_ROOT}),
settings.py
The path here is set in the project file to facilitate unification , In practical applications, it should also be set in public files
MEDIA_URL = "media/uploads/"
MEDIA_ROOT = os.path.join(MEDIA_URL, "")
db The corresponding information is also logged in
Model form
Django Provides ModelForm It can be directly associated with the model , omitted Form Actions defined in the form .
AJAX
Template file , In order to be able to access , You must add csrfmiddlewaretoken Or comment in the view function @csrf_exempt, The first method is recommended
user name :<input type="text" id="username"></input>
password :<input type="password" id="password"></input>
{% csrf_token %}
<button id="submit"> Submit </button>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script> $("#submit").click(function(){
var csrf = $('input[name="csrfmiddlewaretoken"]').val(); $.ajax({
url: '/app1/ajax_login_data', type: "post", data: {
'username': $("#username").val(), 'password': $("#password").val(), 'csrfmiddlewaretoken': csrf }, success: function(data){
console.log(data) }, error: function(jqXHR, textStatus, err){
console.log(arguments); } }); }); </script>
view file
from django.views.decorators.csrf import csrf_exempt
def ajax_login(request):
return render(request, 'app1/ajax.html')
# @csrf_exempt
def ajax_login_data(request):
if request.method == "GET":
HttpResponse(" Internal own url")
username = request.POST.get('username')
password = request.POST.get('password')
print(username)
if username == 'admin' and password == '123456':
return JsonResponse({
'code': 1,
'msg': " Landing successful "
})
else:
print("222")
return JsonResponse({
'code': 0,
'msg': " Login failed "
What is used here is online jquery Address , Also available at settings.py Match as follows , Create... In the root directory of the web site static Catalog , Put in jquery file .
<script src=“/statics/jquery.min.js”></script>
STATIC_URL = '/statics/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "statics"),
]
copyright notice
author[My talented girlfriend],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/175/202206240641393209.html
The sidebar is recommended
- Writing sample code for functions in Python
- Summary of operation methods of Python set (about 20 operation methods), with sample code attached
- Python -- functions
- Anonymous and recursive functions in Python
- How to query the methods (member functions) of a class or an object in Python [using the function dir()]
- Summary of operation methods of Python Dictionary (dict) (about 18 operation methods), with sample code attached
- Collect hot search lists in Python at work, which can be called a fishing artifact
- Running Django and Vue on docker
- Data classification in pandas
- About Python: docxtpl is embedded by default when inserting pictures
guess what you like
How to solve the problem of CSV? (Language Python)
Installation and use of redis (Python)
Python implements sending mail (implements single / group mail verification code)
On the built-in object type of Python -- number (one of the differences between py2 and PY3)
Python God uses a problem to help you solve the problems of formal and actual parameters in Python functions
"Project Euler Python Mini tutorial" 001-010 solution introduction
Most beginners learn Python and web automation. In this way, they learn and give up
Python matrices and numpy arrays
Exciting challenge: Python crawler crawls the cover picture of station B
After installing python3, use the yum command to report an error?
Random recommended
- New features of python3.6, 3.7, 3.8 and 3.9
- Application of Python simplehttpserver
- Python sending mail (single / group) - yagmail module
- After learning these English words, mom doesn't have to worry that I can't learn Python any more
- 1-python+ selenium automated test (detailed tutorial) in the series of exercises of "teach you by hand"
- Cannot unmarshal array into go value of type main
- Analysis of the principle of Python import
- Python quickly saves pictures in wechat official account articles (multiple articles can be specified)
- Python error reporting series (14) -- selenium support for phantom JS has been deprecated
- Python variable data type
- Advanced Python Programming - functions and modules
- Python conditional judgment and loop statements
- Python dictionary nesting
- I want to use Python to write a census management software. I want to ask about the ideas and software involved
- I want to use Python to write a census management software. I want to consult the ideas and software involved.
- Python program has no idea
- How to set the initial position of the cursor in Python Tkinter
- The scrapy framework only gets a set of results. I don't know why (Language Python)
- Code problems in Python
- Python automation framework
- Vscode - offline extension installation tutorial (take Python plug-in installation as an example)
- _ What are the application scenarios in Python
- Python writing yaml file
- On the strange phenomenon of Python objects
- System learning Python -- unit test unittest: Test Report
- Learn Python in this way, and the boss licks back the resume in the trash can: 25K per month
- Guess the age of American mathematician Wiener
- Python machine learning day03
- Random seed()
- Programming science | you may be wrong about Python
- Is Python really worth learning
- What is the charm of python, which is warmly pursued by countless programmers?
- Python is popular for several reasons: These data tell you
- Picture to character drawing in Python, so easy!
- Data type conversion in pandas module
- Python Basics - (1) overview of Python
- Data Science Library Python -- learning of time series data
- Django project - error reporting
- [run the script framework in Django and store the data in the database]
- Complete Python exception handling in ten minutes