[PYTHON] File upload with django

0.0 Main contents

I will summarize about file upload with django (versino3.1 in this article). By reading this article 1 Upload text 2 Upload image 3 Audio upload You can find out how to do it. This article is primarily aimed at django and programming beginners, but assumes that you already know the basics of the django architecture as a whole.

Also, in this article, 1 Start the project with the following command under the post_file directory.

  $ django-admin startproject post_file . 

2 After that, create template, static, and media directories, and assume that the directory structure is as follows.

$ project/(Project directory)
  .
  │── config/(Setting directory)
  │   │── __init__.py
  │   │── settings.py
  │   │── urls.py
  │   │── wsgi.py
  │── post_file_app/(Application directory)
  │   │── __initi__.py  
  │   │── admin.py
  │   │── apps.py 
  │   │── migrations
  │   │   │── __init__.py 
  │   │── models.py 
  │   │── test.py
  │   │── views.py
  │── manage.py
  │── template/ 
  │── static/
  │── media/
  │   │──image/ 
  │   │──audio/ 

1.0 Main flow up to file upload

Regarding file upload, 1 Upload from the administrator screen (by the site administrator) 2 Upload from the user form (by the site user) There are two possibilities, so we will classify them below.

1.1 Upload from the admin screen (by the site admin)

1.1.1 Add the settings to settings.py.

project/config/settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'post_file_app',#Add this
    'media',#Add this
]

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent#Add this
MEDIA_ROOT = os.path.join(BASE_DIR,'media')#Add this
MEDIA_URL = '/media/'#Add this

Instead of storing uploaded images and audio files directly in the database, django stores them in a pre-prepared file and retrieves the file from that path when needed. In the above, the directory to store is specified by MEDIA_ROOT.

In addition, MEDIA_URL is a setting that assigns a url called / media / <file_name> when displaying a file.

1.1.2 Define the layout of the data to be uploaded in model.py

project/post_file_app/model.py


class PostFile(models.Model):
    usersname = models.CharField(max_length=50)#Text upload
    image =models.ImageField(upload_to='images/',verbose_name='image',null=True,blank=True)#Image upload
    audio = models.FileField(default='', upload_to='audio/')#Audio upload
    def __str__(self):
        return self.usersname

Note that CharField, ImageField, and FileField are used properly depending on what you upload. Don't forget to migrate the model with the following two commands.

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

1.1.3 Add settings to admin.py so that you can upload from the administrator screen

You cannot upload from the administrator screen just by defining the PostFile class in model.py. By adding to admin.py as shown below, you can upload from the administrator screen.

project/post_file_app/admin.py



from .models import PostFile
admin.site.register(PostFile)

1.2 Upload from the user form (by the site user)

In this case, in addition to uploading from the administrator screen, a new one 1 Create input form (html file creation, form.py creation) 2 Implementation of validation of uploaded file (logic is described in views.py) (However, I will not write validation myself in this article, so I will write a little code).

1.2.1 Creating an input form

First, prepare an html file. Create a post.html file in the project / template / directory and write it as follows.

project/template/post.html


<!doctype html>
<html lang="en">
    <head>
    </head>
    <body >
    <form method="POST" action='' enctype='multipart/form-data'>{% csrf_token %}
   {{ form.username }}
   {{ form.image }}
   {{ form.audio }}
    </body>
</html>

First of all, encenctype ='multipart / form-data' must be described in the html form tag when uploading an image or audio file. If you omit this, django will not be able to retrieve images and audio files later.

Also, {% csrf_token%} is like a spell and is required when uploading files.

In addition, username, image, audio must match the variable names (username, image, audio) already mentioned in project / post_file_app / model.py.

Next, create a new form.py in post_file_app and add the following to create an input form.

project/post_file_app/form.py


from django import forms
from .models import PostFile


class PostFileForm(forms.ModelForm):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['username'].widget.attrs.update({'placeholder':'text'})
        self.fields['image'].widget.attrs.update({'placehodler':'image upload'})
        self.fields['audio'].widget.attrs.update({'placehodler':'audio upload'})
    class Meta:
        model = TestPost
        fields = ('text','image','audio')

To display the last created form, create a view in views.py and assign a url to the view in urls.py.

project/post_file_app/views.py


from django.shortcuts import render,redirect
from django.views.generic import CreateView
from .forms import PostFileForm

class PostFileView(CreateView):
    def post(self,request,*args,**kwargs):
        form = PostFileForm(request.POST,request.FILES)
        content_dict={
            'form':form
        }
        if not form.is_valid():#Check if the file is entered correctly (validation)
            return render(request,'error.html')#error.html is not created in the article, but please prepare it yourself.
        form.save()
        return redirect('success_page')
    def get(self,request,*args,**kwargs):
        form = PostFileForm(data=request.GET)
        return render(request,'post.html',{'form':form,})

Here, there is a variable called form, but please match it with the form.username, form.image, and form.audio of post.html mentioned above. Also, there are request.POST and request.FILES as arguments of PostFileForm (). The former is what django needs to get text, and the latter to get images and audio files.

project/post_file_app/urls.py


from django.urls import path
from .views import Register,LoginView,LogoutView
from mystudio.views import RenderPostedSong
from .views import PostSongView,TestPostView,TestPostView,RenderTestPost

urlpatterns = [
    path('post_file_view/',PostFileView.as_view(),name='post_file_view'),
    path('success/',success,name='success_page',#View is not defined in this article
    path('error/',error,name='error_page',#View is not defined in this article
]

the end

that's all. You can now upload text, images, and audio files in django.

Recommended Posts

File upload with django
File upload with Flask + jQuery
Create a file uploader with Django
Internationalization with django
CRUD with Django
Django 1.11 started with Python3.6
Django template file organization
Development digest with Django
Output PDF with Django
Markdown output with Django
File operations with open — "../"
Use Gentelella with django
Twitter OAuth with Django
Getting Started with Django 1
Send email with Django
Use LESS with Django
Pooling mechanize with Django
Use MySQL with Django
Start today with Django
Getting Started with Django 2
[Django] Implement image file upload function without using model
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Get started with Django! ~ Tutorial ⑤ ~
Minimal website environment with django
Create an API with Django
Do Django with CodeStar (Python3.8, Django2.1.15)
Deploy Django serverless with Lambda
Python3 + Django ~ Mac ~ with Apache
Draw netCDF file with python
Create a homepage with django
Upload a file to Dropbox
Fast file transfer with fabric
Image upload & customization with django-ckeditor
Get started with Django! ~ Tutorial ④ ~
Getting Started with Python Django (4)
Web application creation with Django
Getting Started with Python Django (3)
Combine FastAPI with Django ORM
Get started with Django! ~ Tutorial ⑥ ~
Bidirectional file transfer with Pythonista 3
Save tweet data with Django
Do AES encryption with DJango
Getting Started with Python Django (6)
Combine two images with Django
Getting Started with Django with PyCharm
Real-time web with Django Channels
Double submit suppression with Django
Django REST framework with Vue.js
Download csv file with python
Use prefetch_related conveniently with Django
Create xlsx file with XlsxWriter
Getting Started with Python Django (5)
Login with django rest framework
Qiita API Oauth with Django
Test Driven Development with Django Part 3
reload in django shell with ipython
Let's upload S3 files with CLI
Steps to develop Django with VSCode
Extract the xz file with python
Test Driven Development with Django Part 4
Load Django modules with an interpreter