0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Djangoスタートアップ その9 (mediaフォルダ編)

Last updated at Posted at 2023-04-14

mediaフォルダとは

ユーザーがアップロードした画像ファイルを保存しておくフォルダ

settings.pymediaルートの設定

  • MEDIA_URL : ブラウザからアクセスする際のアドレス
  • MEDIA_ROOT : 画像ファイルを読み込みに行く先のフォルダ
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

アプリケーション直下のurls.pyに追記

urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

template側でメディアファイルを扱えるように設定する

settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ・・・
                'django.template.context_processors.media'
            ],
        },
    },
]

テンプレートファイルから画像のパスを取得

<img src="{{object.image.url}}" alt="not">

object.imageのみでは正しいURLをしゅとくできないのでちゅうい


参考記事
https://qiita.com/j54854/items/1f0560142e39d888251c
https://itc.tokyo/django/setup-media-root/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?