[PYTHON] Create a file uploader with Django

I updated it because it has old information and ugly code. (2017/03/16)

environment

Final configuration

file_uploader
	├── db.sqlite3
	├── file_uploader
	│   ├── __init__.py
	│   ├── settings.py
	│   ├── urls.py
	│   └── wsgi.py
	├── manage.py
	├── requirements.txt
	└── upload_form
	    ├── __init__.py
	    ├── admin.py
	    ├── apps.py
	    ├── migrations
	    │   ├── 0001_initial.py
	    │   └── __init__.py
	    ├── models.py
	    ├── static
	    │   └── files
	    │       └── __init__.py
	    ├── templates
	    │   └── upload_form
	    │       ├── base.html
	    │       ├── complete.html
	    │       └── form.html
	    ├── tests.py
	    ├── urls.py
	    └── views.py

I think it would be nice if it had a structure like this. __pycache__ is omitted

setup

Project creation

$ pip install Django==1.9.1
$ django-admin.py startproject file_uploader
$ cd file_uploader
$ django-admin.py startapp upload_form
#I want to check which file was uploaded when
$ python manage.py createsuperuser

Change settings.py

settings.py


INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'upload_form', #add to
)

・ ・ ・

LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'

・ ・ ・

I wonder if it should be

Confirm for the time being

$ python manage.py migrate
$ python manage.py runserver

http://127.0.0.1:8000

If you access and the example is out, it's OK

ʻUpload_form` Build App

models.py

upload_form/models.py


from django.db import models
from datetime import datetime

class FileNameModel(models.Model):
    file_name = models.CharField(max_length = 50)
    upload_time = models.DateTimeField(default = datetime.now)

file_name: File name ʻUpload_time`: Upload date and time (default is the current date and time)

views.py

upload_form/views.py


from django.shortcuts import render, redirect
from django.template.context_processors import csrf
from django.conf import settings
from upload_form.models import FileNameModel
import sys, os
UPLOADE_DIR = os.path.dirname(os.path.abspath(__file__)) + '/static/files/'

def form(request):
    if request.method != 'POST':
        return render(request, 'upload_form/form.html')

    file = request.FILES['file']
    path = os.path.join(UPLOADE_DIR, file.name)
    destination = open(path, 'wb')

    for chunk in file.chunks():
        destination.write(chunk)

    insert_data = FileNameModel(file_name = file.name)
    insert_data.save()

    return redirect('upload_form:complete')

def complete(request):
    return render(request, 'upload_form/complete.html')

template

upload_form/templates/upload_form/base.html


<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="viewport" content="content">
        <title>File uploader</title>
    </head>
    <body>
        {% block content %}
            {{ content }}
        {% endblock %}
    </body>
</html>

upload_form/templates/upload_form/form.html


{% extends "upload_form/base.html" %}

{% block title %}Uploader sample{% endblock title %}
{% block content %}
    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>
{% endblock content %}

upload_form/templates/upload_form/complete.html


{% extends "upload_form/base.html" %}

{% block title %}Upload completed{% endblock title %}
{% block content %}
    <div align="center">
        <h1 align="center">Upload completed</h1>
        <a href="{% url 'upload_form:form' %}"><button>Return</button></a>
    </div>
{% endblock content %}

Uploading Maybe there is no upload destination directory! Because you may get angry Create a directory with a structure like ʻupload_form / static / files /`.

URL setting

urls.py

ʻUpload_form / urls.py` is newly created and the following

upload_form/urls.py


from django.conf.urls import url
from upload_form import views

urlpatterns = [
    url(r'^$', views.form, name = 'form'),
    url(r'^complete/', views.complete, name = 'complete'),
]

file_uploader/urls.py


from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('upload_form.urls', namespace = 'upload_form')),
]

Django admin site settings

admin.py

upload_form/admin.py


from django.contrib import admin
from upload_form.models import FileNameModel

class FileNameAdmin(admin.ModelAdmin):
    list_display = ('id', 'file_name', 'upload_time')
    list_display_links = ('id', 'file_name')

admin.site.register(FileNameModel, FileNameAdmin)

Allow data to be viewed and edited from the Django admin site

Migration & launch

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

http://127.0.0.1:8000 When you visit, you'll see a crappy web page. If you upload it properly from there, it will work.

スクリーンショット 2016-08-18 午後3.42.39.png

http://127.0.0.1:8000/admin/ Go to and log in http://127.0.0.1:8000/admin/upload_form/filenamemodel/ Make sure you have the data when you enter! !!

スクリーンショット 2016-08-18 午後3.43.48.png

For some reason, the uploaded files are only iOS Certificate and p12 files, so I'm sorry but I was able to confirm!

The rest is baking or simmering.

When I uploaded a CSV file at my graduate school last year, I read the contents and inserted it into the DB table.

Repository

https://github.com/nnsnodnb/django-file-uploader

Repository link

Recommended Posts

Create a file uploader with Django
Create a homepage with django
Create a large text file with shellscript
Create a VM with a YAML file (KVM)
Create a Django schedule
File upload with django
Create a GUI executable file created with tkinter
Create a PDF file with a random page size
Create a dashboard for Network devices with Django!
Create a one-file hello world application with django
Create a Photoshop format file (.psd) with python
Create a cylinder with open3d + STL file output
Create a dummy data file
Create a Django login screen
Create a heatmap with pyqtgraph
Create a directory with python
Create xlsx file with XlsxWriter
Create a Todo app with the Django REST framework
Create a Todo app with Django ③ Create a task list page
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a Todo app with Django ⑤ Create a task editing function
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Create a 2d CAD file ".dxf" with python [ezdxf]
[Python] Create a file & folder path specification screen with tkinter
Steps to create a Django project
Build a deb file with Docker
Deploy a Django application with Docker
Create a virtual environment with Python!
Create an Excel file with Python3
Create a binary file in Python
Django Tips-Create a ranking site with Django-
Create a 1MByte random number file
Make a filter with a django template
Create a web API that can deliver images with Django
Create a Todo app with Django ① Build an environment with Docker
Create a social integration API for smartphone apps with Django
Create a LINE Bot in Django
[Python] Create a screen for HTTP status code 403/404/500 with Django
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Rails users try to create a simple blog engine with Django
Create a REST API to operate dynamodb with the Django REST Framework
Create and return a CP932 CSV file for Excel with Chalice
Create a Python function decorator with Class
Creating a simple PowerPoint file with Python
Create RESTful APIs with Django Rest Framework
Build a blockchain with Python ① Create a class
Create a model for your Django schedule
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Quickly create an excel file with Python #python
Create a GUI app with Python's Tkinter
Create a star system with Blender 2.80 script
Create a virtual environment with Python_Mac version
Creating a login screen with Django allauth
Create an update screen with Django Updateview
Create a simple web app with flask
Create Excel file with Python + similarity matrix
Create a word frequency counter with Python 3.4
Create your first app with Django startproject
Create a deb file from a python package
A note on enabling PostgreSQL with Django