Django Build upload file system--elaborate form Validation (ii)

Source: Internet
Author: User

The main way I studied Django was http://djangobook.com, and the author's book appeared to have been published. The author's thinking is very refreshing, the explanation is easy to understand, the depth of the place in depth, I like, more than the official Django documents feel much better, the official document is too obscure. These essays are a combination of some examples of Django's Learning Essentials and My Learning experience.

Some Chinese blogs also explain the use of Django to do some small projects, but did not elaborate on the Django principle, that is why to do so, I will be a personal understanding of the various parts of the knowledge point. Hope to help more people, but also want to work with more people to progress.

I configure the Environment: (2017.6.20)

Note : The file system in Windows is represented by a backslash ' \ ', but even under the Windows system, Django still uses the Unix-style slash '/' when it represents the file path.

Os:win7

python:3.6.2

django:1.11.2

Create projects and apps

The first part of each project: Create the project and application, add the application to the settings.py 'installed_app ' , set the default database in settings.py , and synchronize the database data operations are the same, not specifically described, you can refer to my previous examples.

I named the project that uploaded the file as disk, the project name is MySite, the structure after creation is as follows: (disk/templates, disk/uploads, disk/forms.py I created, is not created by the system. Please ignore the section other than MySite, which is not related to this example. )

#application DefinitionInstalled_apps= (    'Django.contrib.admin',    'Django.contrib.auth',    'Django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'Django.contrib.staticfiles',    ' Disk ',)
Create a Form class instance

For the sake of simplicity, in this file upload system, we only design two variables: The user who uploaded the file, and the uploaded file. Django defines a user with a django.forms Library, which makes it easy to display data and validate data in form classes. Save a lot of user's code. django.forms libraries are easy to use, just need to add <form> tag , it is OK to define the corresponding form class. In the example below we have only one <form> tag on the final page, so we just need to define a form class. The common practice of the Django community is to put the form class in a forms.py file, and we'd better follow this rule. Create the disk\forms.py file, and write:

# mysite\disk\forms.py  from Import Forms class UserForm (forms. Form):    = forms. Charfield (max_length =)    = forms. Filefield ()

As you can see, the syntax of the form class is much like the syntax for defining the model, and for each variable you define its domain properties, which I'll talk about in the model section below. In UserForm, we define username, which is a character attribute and also defines UploadFile, which is a file attribute. Both of these variables are not nullable by default, and if they are empty, they are displayed in the HTML page with the corresponding error.

Create models (database tier)

We need to put the user name and the uploaded file path into the database, so we need two fields to design the database:userName and UploadFile. Write in the disk\models.py file:

# disk\models.py  from Import Models # Create your models here. class User (models. Model):    = models. Charfield (max_length = +)    ' disk/upload/')     def __str__ (self):         return Self.username

For the definition of models, there are many things to talk about.

    • Each variable is defined as a certain type of field (field), and Django determines something based on different domains. For example, the type of the domain determines the data type of the variable in the database (for example, I nterger, VARCHAR). For each variable, in the HTML display layer, Django defines it as a separate widget. Finally, what widget shows the variable is also related to the type of the field, such as a charfield variable will eventually appear in the form of <input type= ' text ' > .
    • The following is the definition of each domain type variable, from http://www.djangobook.com/model-definition-reference/. In order to ensure the completeness and accuracy of the interpretation, I will not translate into Chinese:

The following table is an optional parameter that is common to all domains:

    • filefiled Description: This type of variable does not support Primary_key, the unique parameter (see table above). There are two optional parameters:upload_to and storage. ' upload_to ' defines a local file path, which can be a relative path, which is automatically appended to the base_dir directory in the settings.py file. In general, even if a file is uploaded successfully, it will not be saved to the database unless the explicit call to the Save () function occurs. From a performance consideration, the uploaded file is not stored in the database, but the path to the file is stored in the database (if the Save () function is called).
    • After defining the models , to synchronize it to the database, mainly with two commands python manage.py makemigrations, python manage.py migrate

Create views (logical layer)

View views determines how the data is collected and processed, and the user's data is presented to the user, which can be understood as the middleman of the user data (database) to the final rendering page (Web page). This section is typically purely Python code. Open the mysite\disk\views.py file and write:

#mysite\disk\views.py fromDjango.shortcutsImportRender fromDisk.formsImportUserForm fromDisk.modelsImportUserdefuploads (Request):ifRequest.method = ='POST': UserForm=UserForm (Request. POST, request. FILES)ifuserform.isvalid (): User=User () user.username= userform.cleaned_data['UserName'] User.uploadfile= userform.cleaned_data['UploadFile'] User.save ()returnRender (Request,'uploadok.html')    Else: UserForm= UserForm (initial ={'UserName':'Sunshore'})    returnRender (Request,'upload.html', {'UserForm': UserForm})

The views.py file references the UserForm and user (models file) as defined above.

  • For the httprequest.post object, as we said in the previous section, it is no longer described here.
  • The httprequest.files object is also a "class dictionary" object whose ' key ' is the file name, with the HTML file <input type = "File" name = ""/> The ' value ' corresponding to 'key ' is the uploaded file. Note: This object must be in HttpRequest method = ' POST ' and <form> tag contains enctype= "Multipart/form-data " will have a value, otherwise an empty class Dictionary object will be returned.
  • After instantiating the Form class in Django, the isValid () function can be used to check whether the data is valid, and if so, the instance will have the Cleaned_data property, which is a Dictionary object , which contains the Form class data.
  • We first check that HttpRequest is a POST method, then instantiate the Form class, and if the instantiation succeeds, store the data in the database. (Of course, it is not the file itself, but the file path, as mentioned in the last section). If HttpRequest is not a POST method, the user name is initialized to 'Sunshore '.

Create templates (display layer)

We need to create templates to customize the display of the data. Django separates the processing and display of data, the data is processed in views.py , and the data is displayed in templates. By default, TEMPLATES in themysite/mysite/settings.py file defines 'app_dirs ' = True, This means that Django will look for the Templates folder under the files of each application, using the HTML file defined inside it.

We need to create two HTML files in mysite/disk/templates:upload.html and uploadok.html, and write:

#mysite\disk\templates\upload.html<?xml version="1.0"encoding="UTF-8"?> <! DOCTYPE HTML Public"-//W3C//DTD XHTML 1.0 strict//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-STRICT.DTD">"http://www.w3.org/1999/xhtml"xml:lang="en"lang="en">
<style type= "Text/css" >

ul.errorlist{
margin:0;
padding:0;
}
. errorlist li{
Background-color:blue;
Color:white;
Display:block;
Font-size:1.0em;
margin:0 0 1px;
Padding:0 10px;
}
</style>

<meta http-equiv="Content-type"Content="text/html; Charset=utf-8"/> <title>upload file</title>""Method="Post"Enctype="Multipart/form-data">{ {userform.as_p}} {% Csrf_token%}<input type="Submit"Value="OK"/> </form></body>
#mysite\disk\templates\uploadok.html<?xml version="1.0"encoding="UTF-8"?> <! DOCTYPE HTML Public"-//W3C//DTD XHTML 1.0 strict//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-STRICT.DTD">"http://www.w3.org/1999/xhtml"xml:lang="en"lang="en">"Content-type"Content="text/html; Charset=utf-8"/> <title>upload ok</title>'Upload'>back to upload file page </a></body>
 
  
    • The form class automatically generates error messages for the page and returns the results as errorlist . In the HTML file, we can customize the CSS for Errorlist, which makes the error information more prominent. This is the function of the <style> ....</style> piece of code.
    • By default, the format of the form class display member is form.as_p, form.as_table, Form.as_ul These three forms, the arrangement of members under different forms is different. For example, the userform.as_p in this example is shown below :

Userform.as_table Display Results:

Userform.as_ul Display Results:

We can choose the display form of the members according to our own preference. Of course Django also supports customizing the display of all its members. Interested readers can refer to: http://djangobook.com/tying-forms-views.

Setting up the urlconf file

This is a regular expression of the way to define the Httprequest.url and views of the corresponding relationship. In the mysite\urls.py file, enter:

#mysite\urls.py fromDjango.conf.urlsImportpatterns, include, url fromDjango.contribImportAdminadmin.autodiscover () fromDiskImportviews as Disk_viewsurlpatterns= Patterns ("',    #Examples:    #URL (r ' ^$ ', ' mysite2.views.home ', name= ' home '),    #URL (r ' ^blog/', include (' Blog.urls ')),URL (r'^admin/', include (admin.site.urls)), url (r'^upload/$', Disk_views.upload),)

Start the service

Under the mysite folder, terminal command line input: python manage.py runserver

After the user has uploaded the file correctly, we can see this file under the mysite\disk\upload folder, which is defined in the models.py, the reader can try it.

Django Build upload file system--elaborate form Validation (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.