Python+django quickly implement file uploads

Source: Internet
Author: User
For the web open, user login, registration, file upload and so on is the most basic function, for different web frameworks, related articles very much, but after the search found that most of them do not have integrity, for beginners who want to learn web development, there is no way to step-by-step operation of the practice; for Web applications, Including the creation of the database, the development of the front-end page, and the processing of the intermediate logic layer three parts.

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

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

Create projects and apps

#创建项目
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 a mysite2/mysite2/settings.py file and add the disk app to it:

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

Design Model (database)

Open a 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 user name, headimg user to store the path of the uploaded file.

Synchronize the database below

fnngj@fnngj-h24x:~/djpy/mysite2$ python manage.py syncdbcreating tables ... Creating table django_admin_logcreating table auth_permissioncreating table auth_group_permissionscreating table Auth_ groupcreating table auth_user_groupscreating table auth_user_user_permissionscreating table auth_usercreating table django_content_typecreating Table django_sessioncreating table disk_useryou just installed Django ' s auth system, which me Ans You don ' t has any superusers defined. Would to create one now? (yes/no): Yes  input yes/nousername (leave blank to use ' Fnngj '):   username (default current system user name) Email address:fnngj@126.com   Email address password:  password password (again):  Confirm Password Superuser created successfully. 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 a registration page

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

<?xml version= "1.0" encoding= "UTF-8"?>   
 
    

Register

3. Set the template path

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

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

4. Set the URL

From Django.conf.urls import patterns, include, Urlfrom django.contrib import adminadmin.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 runservervalidating models ...  0 Errors Foundmay, 2014-13:49:21django version 1.6.2, using Settings ' mysite2.settings ' starting development 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 normally to indicate that the whole process has gone through. This is also the basic routine of Django development. Readers must be proficient in understanding this basic routine.

complete Form submission
Through the process above, we just string up the process, careful you must find that our register.html file, and did not create a user-submitted form, the views.py file does not have the user submitted information to do processing. We add further to these two documents below.

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

<?xml version= "1.0" encoding= "UTF-8"?>   
 
    

Register

Open mysite2/disk/views.py File:

From django.shortcuts import render,render_to_responsefrom Django import formsfrom 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 the user name, select the local upload file, click "OK"

Throws an error, this error is friendly, so it is not a small error during our operation.

Open the mysite2/mysite2/settings.py file and comment 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 correctly submit the user name and file!

writing data to the database

Although data submissions have 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-8from django.shortcuts Import render,render_to_responsefrom Django import formsfrom django.http Import Httpresponsefrom 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 to complete the file upload.

What is stored in the database?

fnngj@fnngj-h24x:~/djpy/mysite2$ sqlite3 db.sqlite3 SQLite version 3.7.15.2 2013-01-09 11:53:05enter ". Help" for Instructionsenter SQL statements terminated with a ";" Sqlite> select * FROM Disk_user;1 | Alen  

By looking at the database discovery, our database is not the user upload the file itself, but the file storage path.

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support the script home.

  • 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.