[PYTHON] Upload files with Django

Django file upload format

In Django, file uploads are in the form of "setting an address in the DB" and "putting the actual file in the media area"! There is a type that handles Blob type for the time being, but when it comes to operation, it is better to put the actual file on the server and make it accessible at the time of maintenance rather than having the file in the DB. Cool operation is possible ヾ (.> ﹏ <.) ノ ✧ *.

Add file fields to the model

Django has a feature that does all this for you! That is the "** file field **". Just set the type to FileField and set the save destination address in ** upload_to ** and it will be registered automatically!

picture.py



from django.core.validators import FileExtensionValidator
from django.db import models

'''
Image model
@author shibafu
'''
class Picture(models.Model):
    id
    name = models.CharField(max_length=200)
    #Set the file field
    image = models.FileField(upload_to='upload_pict/%Y/%m/%d/', #upload_Set the save destination address in to. If you do this, media_upload under root_pict/2020/02/Saves the image to 10
                             verbose_name='Uploaded image',#It seems to be the name displayed on the management screen. Maybe you don't have to set it
                             validators=[FileExtensionValidator(['jpg','png','gif', ])],#Extension validator. Error when the extension of the uploaded file is different
                             )
    uploader = models.CharField(max_length=200)
    uploadDate = models.DateField()
    updateDate = models.DateField()
    deleteFlg = models.BooleanField()

    def __str__(self):
        return '<Picture:id' + str(self.id) + ', ' + \
            self.name + '(' + str(self.uploader) + ')>'

I will also make a model form

PictUploadForm.py


'''
Model form for image upload
@author shibafu
'''
class PictUploadForm(forms.ModelForm):
    class Meta:
        model = Picture
        fields = ['name', 'image']

Finally, decide the root directory of the save address and the setting is completed!

setting.py


MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Upload file

I like it, but I upload it using the model form. In this format, the request object

PictService.py


'''
A service that performs image-related processing
@author shibafu
'''

class PictService:

    #Add a new image(For image upload form)
    def createFromRequest(self, request):
        pictObj = Picture()
        pictObj.uploader = "The default guest!"
        pictObj.uploadDate = datetime.datetime.today()
        pictObj.updateDate = datetime.datetime.today()
        pictObj.deleteFlg = False

        #Pass both POST and FILE for files
        #By setting instance, you can decide the value that can be automatically set on the server side instead of the request
        pict:PictUploadForm = PictUploadForm(request.POST, request.FILES, instance=pictObj)
        pict.errors
        if pict.is_valid():
        #Check if the value is correct(Validation)
            pict.save()
            #Register value in DB

Let's execute ヾ (.> ﹏ <.) ノ ✧ *.

I will actually upload it! ESrnAT2VAAU5oTz.png

The address is held in the DB ESrnCeyUMAA9kT9.png

The actual file is saved in the media area!

ESrnIckU4AEYYAn.jpg

By creating a function for naming files, you can change the file name when uploading! I was able to implement file upload!

References [Django] How to use the file upload function [Basic settings]

Recommended Posts

Upload files with Django
File upload with django
Let's upload S3 files with CLI
Handle csv files with Django (django-import-export)
Manage Django config files with Python-decouple
Upload & move GCS files with Go
Internationalization with django
CRUD with Django
Permission error when reading Django upload files
Django 1.11 started with Python3.6
Development digest with Django
Output PDF with Django
Markdown output with Django
Use Gentelella with django
Twitter OAuth with Django
Getting Started with Django 1
Send email with Django
Use LESS with Django
Upload files to Google Drive with Lambda (Python)
Pooling mechanize with Django
Configure a module with multiple files in Django
Use MySQL with Django
Start today with Django
Getting Started with Django 2
How to upload files in Django generic class view
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
Getting Started with Python Django (1)
Create a homepage with django
Image upload & customization with django-ckeditor
Sorting image files with Python (2)
Get started with Django! ~ Tutorial ④ ~
Sort huge files with python
Sorting image files with Python (3)
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 ⑥ ~
Sorting image files with Python
Save tweet data with Django
Transfer files with teraterm [Note]
Integrate PDF files with Python
Reading .txt files with Python
Do AES encryption with DJango
Getting Started with Python Django (6)
Combine two images with Django
Getting Started with Django with PyCharm
About handling Django static files
Real-time web with Django Channels
File upload with Flask + jQuery
Handle JSON files with Matlab
Double submit suppression with Django
Django REST framework with Vue.js
Use prefetch_related conveniently with Django
Getting Started with Python Django (5)