[PYTHON] The story of viewing media files in Django

How do I view media files in Django?

First of all, it looks like this to accept file registration with a Web service.

File registration ↓ File display

In particular, Django has a class called ** File Field **, which is dedicated to saving files. Since there are classes called ** upload form ** and ** model ** I think it's pretty easy to do.

The upload side is awkward to write, so the official document may be okay. (File Upload) Roughly speaking, it looks like this

Classes supported by Django function
File field Receive file information from the request and record the binary data in the directory and the file address in the DB
Upload form Set a value in the field of the model (entity in Java)
model It has a field of model (entity in Java). Django's model comes standard with an ORM feature, and DBs and fields are always migrated and synchronized. In addition, save to the model()The method is installed. Auto persistence unit(´ ・ ω ・ `)

First, to set the media file Set the root directory for media files.

Server settings. Django and Nginx settings

Set setting.py as usual.

setting.py


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')   #← Add this
MEDIA_URL = '/media/'

BASE_DIR is two above setting.py, that is, the root directory of the app with ** manage.py **. It means that. Therefore, the root directory of the media file is set to the media directory ** in the same directory as ** manage.py. And I set the URL to access the media file to ** / media / **.

Actually, in this state, even if Django side is OK, Nginx side that receives access Because it gives an error such as "File is too big!".

I'll send you a big image file. I have to write the setting. Let's open the config file

% sudo vim /etc/nginx/conf.d/site.conf $Location of Nginx settings for Ubuntu. If you're a CentOS sect, try a different file

site.conf


server {
   listen  80;
   listen [::]:80;
   server_name sample;
   client_max_body_size 20M; #add to. Set the maximum size of request transmission to 20 Mbytes

   location /static {
       alias /home/The user name you set/App root/static;
   }

   location /media {  #add to. Set media file and URL
       alias /home/The user name you set/App root/media;
   }

   location / {
       proxy_pass http://127.0.0.1:8000;
    }
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       proxy_set_header X-Forwarded-Proto $scheme;
}

Let's make sure that location and Django's media root point to the same location like this (^-^)

This completes the server settings!

How to use the upload function

It's annoying, so I'll break it down and explain (´ ・ ω ・ `) The file field is used by incorporating it into the model like this.

fileModel.py


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

'''
Image model
@author Nozawa
'''
class Picture(models.Model):
    id = models.BigAutoField(primary_key=True,unique=True)
    name = models.CharField(max_length=200)
    image = models.FileField(upload_to='upload_pict/%Y/%m/%d/',
                             verbose_name='Uploaded image',
                             validators=[FileExtensionValidator(['jpg','png','gif', ])],
                             ) #upload_Select the save destination directory with to Select the extension with validators. Verbosity_Set how to display on the management screen with name
    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) + ')>'

The upload form is used like this.

PictUploadForm.py



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

pictureService.py


    def createPicutre(self, 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

In fact, the upload form is a function that omits the original way of writing file uploads. The upload form is by entering the model instance and request. ** A convenient class that automatically sets values for your model **!

Originally, as the official document says, it is written like this

sample.py


            instance = ModelWithFileField(file_field=request.FILES['file']) #The field name is specified in the constructor and set.
            instance.save()

Finally, the upload side display screen will be displayed.

UploadView.py


class UploadView(TemplateView):
    #Initialization process
    def __init__(self):
        self.params = {
            'form': PictUploadForm.PictUploadForm(),
        }
    #Display image form
    def get(self, request):
        #Substitute image object
        return render(request, 'memFrame/Upload screen.html', self.params)

Upload screen.html


<form action="{% url 'pictUpload' %}" method="post" enctype="multipart/form-data"> <!--Set up a multipart and prepare for file upload-->
    {% csrf_token %}
    {{ form.name }}
    {{ form.image }}
    <tr>
        <td>
            <input type="submit" value="Upload an image!"/>
        </td>
    </tr>
</form>

How to use the display function

ViewingView.py


class ViewingView(TemplateView):
    #Image service class
    pictService:PictService = PictService.PictService()
    #Display image form
    def get(self, request):
        #Substitute image object
        pictList:list = self.pictService.findAll()
        self.params = {
            'picts':pictList,
        }

        print(pictList)

        return render(request, 'myapplication/Display screen.html', self.params)

Display screen.html


{% for pict in picts %}
    <h2>{{ pict.name }}</h2>
    <img src='{{pict.image.url}}' width=200> #Specify the URL of the file field in the image tag
{% endfor %}

result

I was able to display the uploaded image ヾ (.> ﹏ <.) ノ ✧ *.

image.png

image.png

Recommended Posts

The story of viewing media files in Django
The story of participating in AtCoder
The story of the "hole" in the file
The meaning of ".object" in Django
The story of sys.path.append ()
The story of finding the optimal n in N fist
The story of reading HSPICE data in Python
The story of building the fastest Linux environment in the world
The story of FileNotFound in Python open () mode ='w'
The story of building Zabbix 4.4
[Apache] The story of prefork
I participated in the translation activity of Django official documents
Django + MongoDB development environment maintenance (in the middle of writing)
The story of a Django model field disappearing from a class
Summary of stumbling blocks in Django for the first time
The story of downgrading the version of tensorflow in the demo of Mask R-CNN.
The story of Python and the story of NaN
Handling of JSON files in Python
Switch the language displayed in Django 1.9
The story of remounting the application server
The story of writing a program
Get the query string (query string) in Django
Django cannot be installed in the development environment of pipenv + pyenv
The story of outputting the planetarium master in pdf format with Pycairo
Test the application of migration files with Django + PostgreSQL (Evil Way)
The story of failing to update "calendar.day_abbr" on the admin screen of django
The story of returning to the front line for the first time in 5 years and refactoring Python Django
Consider the description of Dockerfile (Django + MySQL②)
Get the client's IP address in Django
The story of a Parking Sensor in 10 minutes with GrovePi + Starter Kit
The story of trying to reconnect the client
I tried the asynchronous server of Django 3.0
[Understanding in 3 minutes] The beginning of Linux
Check the behavior of destructor in Python
Understand the benefits of the Django Rest Framework
Django ~ Let's display it in the browser ~
How to check the version of Django
Output tree structure of files in Python
The story of verifying the open data of COVID-19
The story of adding MeCab to ubuntu 16.04
The story of making Python an exe
Notes on creating static files in Django
Read all csv files in the folder
The story of making an immutable mold
The result of installing python in Anaconda
Let's claim the possibility of pyenv-virtualenv in 2021
The story of manipulating python global variables
The story of trying deep3d and losing
The story of deciphering Keras' LSTM model.predict
Hello world instead of localhost in Django
In search of the fastest FizzBuzz in Python
The story of blackjack A processing (python)
The story of pep8 changing to pycodestyle
The story of using mysqlclient because PyMySQL cannot be used with Django 2.2
Try hitting the Spotify API in Django.
Consider the description of docker-compose.yml (Django + MySQL ③)
How to uniquely identify the source of access in the Django Generic Class View
How to count the number of elements in Django and output to a template
Test the number of times you have thrown a query (sql) in django
The story of Django creating a library that might be a little more useful
I want to see a list of WebDAV files in the Requests module