[Django] Implement image file upload function without using model

Introduction

When uploading an image file with the Django app, I think it's a standard practice to use ImageField to save it in the DB. However, the app I made the other day in practice needs to save the file in a specific folder instead of the DB ** due to integration with other systems **, and it took a while to find out how to do it, so I wrote an article. I will leave it.

Conclusion

This can be achieved using ** forms.ImageField **.

sample

Below is a sample of the minimum configuration.

top page image.png

The screen changes when you select an appropriate image file and send it. image.png

If you look at the base directory of the project, a "media_root" folder is created, and the uploaded file is saved in it. image.png

If you upload a file other than an image, an error message will be displayed. image.png

Source

forms.py


import datetime
from django import forms
from django.core.files.storage import default_storage


class FileUploadSampleForm(forms.Form):
    file = forms.ImageField()

    def save(self):
        """Method to save file"""
        now_date = datetime.datetime.now().strftime('%Y%m%d%H%M%S')  #Get to give the current time to the file name
        upload_file = self.files['file']  #Get the upload file from the form
        file_name = default_storage.save(now_date + "_" + upload_file.name, upload_file)  #Save file The return value is the name of the file actually saved
        return default_storage.url(file_name)

views.py


from django.shortcuts import render
from django.views.generic import View
from .forms import FileUploadSampleForm


class IndexView(View):
    def get(self, request, *args, **kwargs):
        """Method for GET request"""
        form = FileUploadSampleForm
        return render(request, 'fileUploadSample/index.html', {"form": form})

    def post(self, request, *args, **kwargs):
        """Method for POST request"""
        form = FileUploadSampleForm(request.POST, request.FILES)

        if not form.is_valid():
            return render(request, 'fileUploadSample/index.html', {"form": form})

        filename_save = form.save()

        context = {
            'form': form,
            'filename_save': filename_save,
        }
        return render(request, 'fileUploadSample/index.html', context)


index = IndexView.as_view()

index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{% url 'fileUploadSample:index' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}

    {#forms.Show Image Field#}
    {{ form.file }}
    <br><br>

    {#Show error message#}
    {% for field in form %}
        {% if form.errors %}
            <font color=#CC3300>{{ field.errors }}</font><br>
        {% endif %}
    {% endfor %}

    {#Show saved file name#}
    {% if filename_save %}
file name{{ filename_save }}It was saved in.
        <br><br>
    {% endif %}

    <input type="submit" value="Send"/>
</form>
</body>
</html>

urls.py


from django.urls import path
from . import views

app_name = 'fileUploadSample'
urlpatterns = [
    path('', views.index, name='index'),
]

Please add the following to settings.py.

settings.py


MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')

You can also use ** forms.FileField ** to support uploading files other than images (form.is_valid () will eliminate the error even if it is not an image file).

that's all. Thank you for your hard work: cat2:

Recommended Posts

[Django] Implement image file upload function without using model
File upload with django
Create a Python image in Django without a dummy image file and test the image upload
Image upload function with Vue.js + Flask
WEB application development using Django [Model definition]
Image recognition model using deep learning in 2016
Implement OAuth without using client library (Java)
Get a reference model using Django Serializer
Implement a Custom User Model in Django
Run a Python file from html using Django