찾다
백엔드 개발파이썬 튜토리얼python+django는 파일 업로드를 빠르게 구현합니다.

웹 개발에 있어서는 사용자 로그인, 회원가입, 파일 업로드 등이 가장 기본적인 기능인데, 다양한 웹 프레임워크에 대한 관련 글들이 많이 있지만 검색해 보니 대부분이 완벽하지 않은 분들을 위한 것이었습니다. 웹을 배우고 싶습니다. 초보 개발자의 경우 웹 애플리케이션을 단계별로 연습할 방법이 없습니다. 여기에는 데이터베이스 생성, 프런트 엔드 페이지 개발, 중간 논리 레이어 처리의 세 부분이 포함됩니다. .

이 시리즈는 조작성에 중점을 두고 Django 웹 프레임워크를 통해 몇 가지 간단한 기능을 구현하는 방법을 소개합니다. 각 장은 완전하고 독립적입니다. 초보 사용자도 실습을 통해 웹 개발 과정을 직접 체험해 볼 수 있습니다. 진행 과정에서 자세한 내용은 관련 문서를 참고하시기 바랍니다.

이 작업을 위한 환경:
===================
deepin linux 2013 (우분투 기반)
파이썬 2.7
장고 1.6.2
===================

프로젝트 및 애플리케이션 만들기                                                                                            #프로젝트 만들기

fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite2

fnngj@fnngj-H24X:~/djpy$ cd mysite2
#프로젝트 아래에 디스크 애플리케이션 생성
fnngj@fnngj-H24X:~/djpy/mysite2$ python 관리.py 시작앱 디스크


디렉터리 구조는 다음과 같습니다.


mysite2/mysite2/settings.py 파일을 열고 여기에 디스크 애플리케이션을 추가합니다.


 # Application definition

INSTALLED_APPS = (
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'disk',
)
디자인 모델(데이터베이스)

                                           mysite2/disk/models.py 파일을 열고 다음 내용을 추가하세요


두 개의 필드를 생성합니다. username user는 사용자 이름을 저장하고 headImg user는 업로드된 파일의 경로를 저장합니다.
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

다음은 데이터베이스 동기화입니다


최종 생성된 disk_user 테이블은 models.py에서 생성된 클래스입니다. Django는 이들 사이의 통신을 제공합니다.
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)


뷰 만들기

                               1. mysite2/disk/views.py 파일을 엽니다



2. 등록 페이지 만들기
from django.shortcuts import render,render_to_response

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

먼저 mysite2/disk/ 디렉토리에 template 디렉토리를 생성한 다음 mysite2/disk/templates/ 디렉토리에 Register.html 파일을 생성합니다.



3. 템플릿 경로 설정
<&#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 id="register">register</h1>
</body>
</html>
mysite2/mysite2/settings.py 파일을 열고 하단에 을 추가합니다.


4. URL 설정
#template
TEMPLATE_DIRS=(
  '/home/fnngj/djpy/mysite2/disk/templates'
)


5. 서비스 시작
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'),
)


6. http://127.0.0.1:8000/disk/
를 방문하세요.
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.

등록 페이지가 정상적으로 열리면서 전체 과정이 완료되었음을 알립니다. 이는 Django 개발의 기본 루틴이기도 합니다. 독자는 이 기본 루틴을 능숙하게 이해해야 합니다.

完善表单提交                                                                                            
通过上面的过程,我们只是把过程串了起来,细心你一定发现,我们的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 id="register">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> 

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

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

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?Apr 26, 2025 am 12:13 AM

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?Apr 26, 2025 am 12:12 AM

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?Apr 26, 2025 am 12:05 AM

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.

파이썬 목록에서 요소에 어떻게 액세스합니까?파이썬 목록에서 요소에 어떻게 액세스합니까?Apr 26, 2025 am 12:03 AM

ToaccesselementsInapyThonlist, 사용 인덱싱, 부정적인 인덱싱, 슬라이스, 오리 화.

어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?Apr 25, 2025 am 12:28 AM

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?Apr 25, 2025 am 12:24 AM

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 ​​있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?Apr 25, 2025 am 12:21 AM

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구