├── .gitignore ├── LICENSE ├── README.md ├── manage.py ├── requirements.txt └── uploads ├── __init__.py ├── core ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20160801_0816.py │ └── __init__.py ├── models.py ├── templates │ └── core │ │ ├── home.html │ │ ├── model_form_upload.html │ │ └── simple_upload.html ├── tests.py └── views.py ├── settings.py ├── templates └── base.html ├── urls.py └── wsgi.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | .DS_Store 92 | 93 | staticfiles 94 | media 95 | *.sqlite3 96 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Simple is Better Than Complex 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple File Upload Example 2 | 3 | Example used in the blog post [How to Upload Files With Django](https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html) 4 | 5 | ## Running Locally 6 | 7 | ```bash 8 | git clone https://github.com/sibtc/simple-file-upload.git 9 | ``` 10 | 11 | ```bash 12 | pip install -r requirements.txt 13 | ``` 14 | 15 | ```bash 16 | python manage.py migrate 17 | ``` 18 | 19 | ```bash 20 | python manage.py runserver 21 | ``` 22 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "uploads.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==1.9.8 2 | -------------------------------------------------------------------------------- /uploads/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sibtc/simple-file-upload/4e2e0e8aa4e468a4bd606686836196c451678ab8/uploads/__init__.py -------------------------------------------------------------------------------- /uploads/core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sibtc/simple-file-upload/4e2e0e8aa4e468a4bd606686836196c451678ab8/uploads/core/__init__.py -------------------------------------------------------------------------------- /uploads/core/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /uploads/core/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class CoreConfig(AppConfig): 7 | name = 'core' 8 | -------------------------------------------------------------------------------- /uploads/core/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | from uploads.core.models import Document 4 | 5 | 6 | class DocumentForm(forms.ModelForm): 7 | class Meta: 8 | model = Document 9 | fields = ('description', 'document', ) 10 | -------------------------------------------------------------------------------- /uploads/core/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.8 on 2016-08-01 08:14 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='Document', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('description', models.CharField(blank=True, max_length=255)), 21 | ('document', models.FileField(upload_to=b'')), 22 | ('uploaded_at', models.DateTimeField(auto_now_add=True)), 23 | ], 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /uploads/core/migrations/0002_auto_20160801_0816.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.8 on 2016-08-01 08:16 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('core', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AlterField( 16 | model_name='document', 17 | name='document', 18 | field=models.FileField(upload_to='documents/'), 19 | ), 20 | ] 21 | -------------------------------------------------------------------------------- /uploads/core/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sibtc/simple-file-upload/4e2e0e8aa4e468a4bd606686836196c451678ab8/uploads/core/migrations/__init__.py -------------------------------------------------------------------------------- /uploads/core/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.db import models 4 | 5 | 6 | class Document(models.Model): 7 | description = models.CharField(max_length=255, blank=True) 8 | document = models.FileField(upload_to='documents/') 9 | uploaded_at = models.DateTimeField(auto_now_add=True) 10 | -------------------------------------------------------------------------------- /uploads/core/templates/core/home.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | 3 | {% block content %} 4 |
Uploaded files:
14 |File uploaded at: {{ uploaded_file_url }}
14 | {% endif %} 15 | 16 | 17 | {% endblock %} -------------------------------------------------------------------------------- /uploads/core/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /uploads/core/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from django.conf import settings 3 | from django.core.files.storage import FileSystemStorage 4 | 5 | from uploads.core.models import Document 6 | from uploads.core.forms import DocumentForm 7 | 8 | 9 | def home(request): 10 | documents = Document.objects.all() 11 | return render(request, 'core/home.html', { 'documents': documents }) 12 | 13 | 14 | def simple_upload(request): 15 | if request.method == 'POST' and request.FILES['myfile']: 16 | myfile = request.FILES['myfile'] 17 | fs = FileSystemStorage() 18 | filename = fs.save(myfile.name, myfile) 19 | uploaded_file_url = fs.url(filename) 20 | return render(request, 'core/simple_upload.html', { 21 | 'uploaded_file_url': uploaded_file_url 22 | }) 23 | return render(request, 'core/simple_upload.html') 24 | 25 | 26 | def model_form_upload(request): 27 | if request.method == 'POST': 28 | form = DocumentForm(request.POST, request.FILES) 29 | if form.is_valid(): 30 | form.save() 31 | return redirect('home') 32 | else: 33 | form = DocumentForm() 34 | return render(request, 'core/model_form_upload.html', { 35 | 'form': form 36 | }) 37 | -------------------------------------------------------------------------------- /uploads/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for uploads project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.9.8. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.9/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'e#-^aknk(5k)ej6rh#h$i(%h(m9)-j*lwrc_1dxnk=a@-mixlt' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 41 | 'uploads.core' 42 | ] 43 | 44 | MIDDLEWARE_CLASSES = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 51 | 'django.contrib.messages.middleware.MessageMiddleware', 52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53 | ] 54 | 55 | ROOT_URLCONF = 'uploads.urls' 56 | 57 | TEMPLATES = [ 58 | { 59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 | 'DIRS': [os.path.join(BASE_DIR, 'uploads/templates'),], 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | 'django.template.context_processors.media', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'uploads.wsgi.application' 75 | 76 | 77 | # Database 78 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 79 | 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django.db.backends.sqlite3', 83 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 84 | } 85 | } 86 | 87 | 88 | # Password validation 89 | # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators 90 | 91 | AUTH_PASSWORD_VALIDATORS = [ 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 103 | }, 104 | ] 105 | 106 | 107 | # Internationalization 108 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 109 | 110 | LANGUAGE_CODE = 'en-us' 111 | 112 | TIME_ZONE = 'UTC' 113 | 114 | USE_I18N = True 115 | 116 | USE_L10N = True 117 | 118 | USE_TZ = True 119 | 120 | 121 | # Static files (CSS, JavaScript, Images) 122 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 123 | 124 | STATIC_URL = '/static/' 125 | STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 126 | 127 | MEDIA_URL = '/media/' 128 | MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 129 | -------------------------------------------------------------------------------- /uploads/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |