[PYTHON] [Django] About static file related settings (images, videos)

I tried to summarize the setting method of image files etc. with Django

What is a static file?

--css file --js file

A file whose contents do not change due to a request from a client such as is called a static file. This time, I will summarize the settings of ** static files such as image files and video files that are ** uploaded by users **. Please refer to here for css files, js files, images that do not need to be uploaded by users, etc. https://qiita.com/Suchmos7/items/eb61727a3f65883028a6

Settings in Setting.py

There are three main parameters that need to be set.

MEDIA_URL Specify the URL for static file (img, video) distribution. If you set as follows in settings.py http (s): // host name/media/image file name You will be able to access it with.

settings.py


MEDIA_URL = '/media/'

MEDIA_ROOT Image save destination Create a media folder in the same hierarchy as manage.py in advance.

In the case of css file and js file, the variable called STATIC_ROOT describes the save destination of the file for production, the variable called STATICFILES_DIRS is used in the development environment, and it is switched to STATIC_ROOT at the time of production, but in the case of images and videos there is no. So I will use MEDIA_ROOT from the beginning.

settings.py


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

By the way, BASE_DIR is a path that points directly under the project, and is a variable defined in settings.py as follows.

settings.py


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

Settings in urls.py

urls.py


from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app1.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

First, import settings and static. Then add it to the urlpatterns variable as above. Specify the delivery URL of the static file in the first argument and the save destination of the static file in the document_root argument. This will link the URL to the save destination, and when you access the URL, it will lead to the save destination of the static file.

How to call in html template

Image (video) files can be divided into the following two types.

--For image data that does not correlate with the database (HP background image, etc.) In this case, it will be a group of files that will not receive uploads from users first. Therefore, it is not treated as MEDIA_ROOT in the first place. This type is treated the same as a css file or js file. Therefore, please refer to the URL below for how to call it in the template.

About static file settings (css, js)

--In the case of image data that correlates with the database (profile image for each user, etc.) I think that the images uploaded by users are basically registered in the model and the data is divided for each user. And although I won't explain it in this article, Django's Model class has ImageField, FileField, etc., and I will save the URL of the uploaded image in that field. An example of model is written below.

models.py


from django.db import models

class Book(models.Model):
        title = models.CharField(max_length=100)
        image = models.ImageField(upload_to="/image/book/")

        class Meta:
               db_table = 'Book'

In ImageField, set upload_to as an argument. This describes the path under MEDIA_ROOT. In this case, the image save destination is the image below.

--manage.py
 Lconfig
 Lmedia--image--book--Designated destination
               Latuhor
        Lvideo

Now, how to call this ImageField and FileField in the template

  1. Pass the model instance when rendering html
  2. Extract the url with the model instance.field name.url is.

views.py


from django.shortcuts import render,redirect

from ./models import Book


def imageshowfunc(request):
      book = Book.obejects.get(title='Interesting book') #BookモデルからタイトルがInteresting bookを検索し取得
      return render(request, 'imageshow.html', {'book':book}) #Pass a book instance as a dictionary argument

imageshow.html


{%if book.image %}
<img src="{{ book.image.url }}"><!--instance.Field name.url-->
{% endif %} <!--If there is no this if statement and there is no image file, an error will be thrown out.-->

A brief explanation of how settings.py works

When you write MEDIA_ROOT in settings.py and migrate it, django will automatically set the image save destination to MEDIA_ROOT. Therefore, you can upload an image without adding anything to the url pattern in urls.py, and the image will be saved in the Path specified by MEDIA_ROOT. ** MEDIA_ROOT specifies the save destination of the image. ** **

However, if you don't set the url pattern when you want to call that image, django won't know where to look and you'll get an error. In other words, the ** url pattern specifies the image reference destination and delivery URL for django. ** **

Recommended Posts

[Django] About static file related settings (images, videos)
[Django] About static file related settings (css, js)
Django static file (static) related settings summary
About handling Django static files
Django tutorial summary for beginners by beginners ⑥ (static file)
Django related sites
django default settings
Django + MySQL settings
Django URL settings