Python + django quick file Upload

Source: Internet
Author: User
This article mainly introduces django's quick file upload and some simple functions through the djangoweb framework. For web, user login, registration, and file upload are the most basic functions. There are many articles related to different web frameworks, however, most of the search results do not have integrity. for beginners who want to learn about web development, they cannot perform operations step by step. for web applications, including database creation, development of front-end pages and processing of the intermediate logic layer.

This series focuses on operability and introduces how to implement some simple functions through the django web framework. Each chapter is complete and independent. Beginners can understand the web development process in the hands-on process. for details, see relevant documents.

Environment in this tutorial:
==============================
Deepin linux 2013 (based on ubuntu)
Python 1, 2.7
Django 1.6.2
==============================

Create a project and an application

# Creating a project
Fnngj @ fnngj-H24X :~ /Djpy $ django-admin.py startproject mysite2
Fnngj @ fnngj-H24X :~ /Djpy $ cd mysite2
# Create a disk application under the project
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 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 the mysite2/disk/models. py file and add the following content:

from django.db import models# Create your models here.class User(models.Model):  username = models.CharField(max_length = 30)  headImg = models.FileField(upload_to = './upload/')  def __unicode__(self):    return self.username

Create two fields: username, username, and headImg.

Perform the following database synchronization:

Fnngj @ fnngj-H24X :~ /Djpy/mysite2 $ python manage. py syncdbCreating tables... creating table partition table auth_permissionCreating table partition table auth_groupCreating table auth_user_groupsCreating table partition table auth_userCreating table partition table django_sessionCreating table disk_userYou just installed Django's auth certificate E M, which means you don't have any superusers defined. wocould you like to create one now? (Yes/no): yes input yes/noUsername (leave blank to use 'fnngj'): user name (default system user name) Email address: fnngj@126.com Email address Password: password (again): confirm the 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 created in models. py. Django provides a ing between them.

Create View
1. open the 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

First, create the templates directory under the mysite2/disk/directory, and then create the register.html file under 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:

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

4. set 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 20, 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. access http: // 127.0.0.1: 8000/disk/

The registration page can be opened normally, indicating that the entire process has passed. This is also the basic way for Django development. Readers must be familiar with this basic routine.

Complete form submission
After reading the complete process, we just concatenate the process and find that our register.html file does not create a user-submitted form, and the views. py file does not process the information submitted by the user. Below we will further supplement these two files.

Open the mysite2/disk/templates/register.html file:

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

Open the 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

Enter the user name, select local file upload, and click "OK"

Throw 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 out 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, and we can submit the user name and file normally!

Write data to the database

Although data submission has been implemented, the user name and file are not actually written to the database. We will further improve 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 (): # obtain the form information username = uf. cle Aned_data ['username'] headImg = uf. cleaned_data ['headimg '] # write database user = User () user. username = username user. headImg = headImg user. save () return HttpResponse ('upload OK! ') Else: uf = UserForm () return render_to_response('register.html', {'U': uf })

Refresh the http: // 127.0.0.1: 8000/disk/page again to complete file upload.

What is saved 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  | upload/desk.jpgsqlite> 

Through viewing the database, we found that what we store in our database is not the file uploaded by the user, but the file storage path.

The above is all the content of this article. I hope it will be helpful to everyone's learning, and I hope you can support your own home.

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.