Python+django Fast implementation File upload _python

Source: Internet
Author: User
Tags auth file upload sessions sqlite xmlns

For the web to open, the user login, registration, file upload, etc. is the most basic function, for different web frameworks, the relevant articles are very many, but after searching found that most of them do not have integrity, for the novice who want to learn web development can not be a step-by-step operation practice; for Web applications, Including the creation of the database, front-end page development, as well as the middle of the logic layer of the processing of three parts.

This series is primarily operable and describes how to implement some simple functions through the Django Web framework. Each chapter has integrity and independence. Use the novice in the process of hands-on experience in the process of web development, the process of details please refer to the relevant documentation.

The environment for this operation:
===================
Deepin Linux 2013 (based on Ubuntu)
Python 2.7
Django 1.6.2
===================

creating projects and Applications

#创建项目
fnngj@fnngj-h24x:~/djpy$ django-admin.py Startproject Mysite2
fnngj@fnngj-h24x:~/djpy$ CD Mysite2
#在项目下创建一个disk应用
fnngj@fnngj-h24x:~/djpy/mysite2$ python manage.py startapp disk

The directory structure is as follows:

Open the mysite2/mysite2/settings.py file and add the disk application:

 # application definition

Installed_apps = (
 ' django.contrib.admin ',
 ' Django.contrib.auth ',
 ' Django.contrib.contenttypes ',
 ' django.contrib.sessions ', '
 django.contrib.messages ',
 ' Django.contrib.staticfiles ',
 ' disk ',
)

Design Model (database)

Open the mysite2/disk/models.py file and add the following

From django.db import Models

# Create your models here.
Class User (models. Model):
 username = models. Charfield (max_length =)
 headimg = models. Filefield (upload_to = './upload/')

 def __unicode__ (self): return
  Self.username

Create two fields, username the user to store the user name, headimg the user to store the path of the uploaded file.

Synchronization of the database below

fnngj@fnngj-h24x:~/djpy/mysite2$ python manage.py syncdb
creating Tables
... Creating table Django_admin_log
Creating table auth_permission
creating table Auth_group_permissions
Creating table Auth_group
Creating table auth_user_groups
creating table Auth_user_user_permissions
Creating table Auth_User
Creating table Django_content_type
Creating table django_session
creating Table disk_user you

just installed Django ' s auth system, which means you don ' t have any superusers defined.
Would to create one now? (yes/no): Yes enter yes/no

Username (leave blank to use ' Fnngj '):  user name (default current system username)
Email Address: fnngj@126.com  Email address
Password: password
Password (again): Confirm Password
superuser created.
Installing Custom SQL ...
Installing Indexes
... Installed 0 object (s) from 0 fixture (s)

The last generated Disk_user table is the class that I created in our models.py. Django provides a correspondence between them.

Create a View
1. Open mysite2/disk/views.py File

From django.shortcuts import render,render_to_response

# Create your views here.
def register (Request): Return
 render_to_response (' register.html ', {})

2. Create registration page

Create the Templates directory under the mysite2/disk/directory, and then create the register.html file in the mysite2/disk/templates/directory:

<?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" >
 
 

3, set the template path

Open the mysite2/mysite2/settings.py file and add at the bottom:

#template
template_dirs= (
 '/home/fnngj/djpy/mysite2/disk/templates '
)

4, set the URL

From Django.conf.urls import patterns, include, URLs from

django.contrib import admin
admin.autodiscover ()

Urlpatterns = Patterns (',
 # Examples:
 # URL (r ' ^$ ', ' mysite2.views.home ', name= ' home '),
 # URL (r ' ^blog/', Include (' Blog.urls '),

 url (r ' ^admin/', include (Admin.site.urls)),
 URL (r ' ^disk/', ' disk.views.register '),
)

5, start the service

fnngj@fnngj-h24x:~/djpy/mysite2$ python manage.py runserver
validating models ...

0 errors found May
, 2014-13:49:21
Django version 1.6.2, using Settings ' mysite2.settings '
starting dev Elopment Server at Http://127.0.0.1:8000/
Quit the server with Control-c.

6. Visit http://127.0.0.1:8000/disk/

The registration page can be opened to show that the whole process has gone through. This is also the basic pattern of Django development. Readers must be proficient in understanding this basic routine.

Refine form submission
Through the above process, we just string up the process, careful you must find that our register.html file, and did not create user-submitted forms, views.py file does not have to deal with the information submitted by the user. We would like to add further to these two documents below.

Open mysite2/disk/templates/register.html File:

<?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" >
 
 

Open mysite2/disk/views.py File:

From django.shortcuts import render,render_to_response from
Django Import forms from
django.http import HttpResponse
# Create your views here.

Class UserForm (forms. Form):
 username = forms. Charfield ()
 headimg = forms. Filefield ()

def Register (Request):
 if Request.method = = "POST":
  uf = UserForm (Request. Post,request. FILES)
  if Uf.is_valid (): Return
   httpresponse (' Upload ok! ')
 else:
  uf = UserForm () return
 render_to_response (' register.html ', {' UF ': uf})

Refresh the http://127.0.0.1:8000/disk/page again

Fill in User name, select Local upload file, click "OK"

Throw an error, this error is more friendly, so it is not a small error in our operation process.

Open the mysite2/mysite2/settings.py file and annotate the following line of code:

middleware_classes = (
 ' django.contrib.sessions.middleware.SessionMiddleware ',
 ' Django.middleware.common.CommonMiddleware ',
 # ' Django.middleware.csrf.CsrfViewMiddleware ',
 ' Django.contrib.auth.middleware.AuthenticationMiddleware ',
 ' Django.contrib.messages.middleware.MessageMiddleware ',
 ' Django.middleware.clickjacking.XFrameOptionsMiddleware ',
)

Refresh the http://127.0.0.1:8000/disk/page again, we will be able to normal user name and file submitted!

write data to the database

Although the submission of the data has been implemented, the user name and file are not actually written to the database. We are here to further refine the mysite2/disk/views.py file:

#coding =utf-8 from
django.shortcuts import render,render_to_response from
Django Import forms
from Django.http import HttpResponse from
disk.models import User

# Create your views here.
Class UserForm (forms. Form):
 username = forms. Charfield ()
 headimg = forms. Filefield ()

def Register (Request):
 if Request.method = = "POST":
  uf = UserForm (Request. Post,request. FILES)
  if Uf.is_valid ():
   #获取表单信息
   username = uf.cleaned_data[' username ']
   headimg = uf.cleaned_ data[' headimg ']
   #写入数据库
   user = user ()
   user.username = Username
   user.headimg = headimg
   User.save () return
   httpresponse (' Upload ok! ')
 else:
  uf = UserForm () return
 render_to_response (' register.html ', {' UF ': uf})

Refresh the http://127.0.0.1:8000/disk/page again and finish uploading the file.

What is stored in the database?

fnngj@fnngj-h24x:~/djpy/mysite2$ sqlite3 db.sqlite3 
SQLite version 3.7.15.2 2013-01-09
Enter ". Help" For instructions
Enter SQL statements terminated with a ";"
Sqlite> select * from Disk_user;
1 | Alen | Upload/desk.jpg
sqlite> 

By looking at the database, we found that our database is not a user-uploaded file itself, but a file storage path.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.