Home  >  Article  >  Backend Development  >  python+django quickly implements file upload

python+django quickly implements file upload

WBOY
WBOYOriginal
2016-12-05 13:27:121804browse

For web development, user login, registration, file upload, etc. are the most basic functions. There are many related articles for different web frameworks, but after searching, I found that most of them are not complete. For those who want to learn web development For novices, there is no way to practice step by step; for web applications, it includes the creation of the database, the development of the front-end page, and the 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. Novice users can experience the process of web development through hands-on experience. Please refer to relevant documents for details during the process.

Environment for this operation:
===================
deepin linux 2013 (based on ubuntu)
python 2.7
Django 1.6.2
===================

Create projects and applications                                                                                    ​

#CreateProject

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 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 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 user stores the user name, and headImg user stores the path of the uploaded file.


The following is the synchronization of the database


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 you like to create one now? (yes/no): yes  输入yes/no

Username (leave blank to use 'fnngj'):   用户名(默认当前系统用户名)
Email address: fnngj@126.com   邮箱地址
Password:  密码
Password (again):  确认密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

The finally generated disk_user table is the class created in our models.py. Django provides a correspondence 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 in the mysite2/disk/ directory, and then create the register.html file in the mysite2/disk/templates/ directory:

<&#63;xml version="1.0" encoding="UTF-8"&#63;> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title></title>
</head>
<body>
<h1>register</h1>
</body>
</html>

3. Set 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 URL

from django.conf.urls import patterns, include, url

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 20, 2014 - 13:49:21
Django 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/

If the registration page can be opened normally, it means that the entire process has been completed. This is also the basic routine of Django development. Readers must be proficient in understanding this basic routine.

完善表单提交                                                                                            
通过上面的过程,我们只是把过程串了起来,细心你一定发现,我们的register.html 文件,并没有创建用户提交的表单,views.py文件中也并没有对用户提交的信息做处理。下面我们就针对这两个文件进一步的补充。

打开mysite2/disk/templates/register.html 文件:

<&#63;xml version="1.0" encoding="UTF-8"&#63;> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title></title>
</head>
<body>
<h1>register</h1>
<form method="post" enctype="multipart/form-data" >
{{uf.as_p}}
<input type="submit" value="ok"/>
</form>
</body>
</html>

打开mysite2/disk/views.py 文件:

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})

再次刷新http://127.0.0.1:8000/disk/ 页面

填写用户名,选择本地上传文件,点击“ok”

抛出一个错误,这个错误比较友好,所以不是我们操作过程中的小错误。

 打开mysite2/mysite2/settings.py文件,将下面一行代码注释:

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',
)

再次刷新http://127.0.0.1:8000/disk/ 页面,我们就可以正常将用户名和文件提交了!

将数据写入数据库         

虽然已经实现了数据的提交,但用户名与文件并没有真正的写入到数据库。我们来进一步的完善mysite2/disk/views.py 文件:

#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})

再次刷新http://127.0.0.1:8000/disk/ 页面,完成文件的上传。

那数据库中保存的是什么呢?

fnngj@fnngj-H24X:~/djpy/mysite2$ sqlite3 db.sqlite3 
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from disk_user;
1 | Alen  | upload/desk.jpg
sqlite> 

通过查看数据库发现,我们数据库中存放的并非用户上传的文件本身,而是文件的存放路径。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn