簡體   English   中英

如何在 Django + React 中提供媒體文件

[英]How to Serve Media Files in Django + React

我對在 Django 上提供媒體文件並做出反應感到困惑。 這是我的代碼:

這是我的 settings.py :

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'build/static'),
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_URL = "/media/"

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

網址.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-user/', include('landingpage.urls')),
    path('', TemplateView.as_view(template_name='index.html'))
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

在 react 上渲染它:

<img
  src="/img/logo.jpeg"  // is it true?
/>

我將我的圖像放在 build/img 文件夾中。 當我用 localhost 3000 打開它時,它會呈現,但是當我用 localhost 8000 打開時,我找不到此圖像鏈接的錯誤http://127.0.0.1:8000/img/logo.jpeg

我的問題是:

圖片放在哪里? 我應該創建媒體文件夾來存儲我的所有圖像還是將其放在 build/image 文件夾中? 如何在反應中指定圖像的 src 鏈接?

謝謝。

在您的原始配置中,Django 在媒體目錄中查找文件,而不是在 build/img 目錄中

從更改媒體文件設置

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

如果您在評論中提到的將圖像存儲在build/img文件夾中,那么MEDIA_URLMEDIA_ROOT應該像

MEDIA_URL = "/img/" #edited MEDIA_ROOT = os.path.join(BASE_DIR, 'build/img') #if the build dir is in root directory, if not then change it accordingly

現在您可以使用This URL Pattern http://127.0.0.1:8000/img/logo.jpeg 中的訪問圖像文件

回答:

  • 將 react 鏡像放到public/static react 項目目錄中,這樣它們就會被移動到build/static ,然后作為其他靜態文件
  • 在反應中有一個叫做PUBLIC_LINK東西。 我建議閱讀這個答案

我可以為生產中的 react+django 提出更通用的方法:

  • settings.py創建 3 個變量:
    • REACT_DIR – 用於你的REACT_DIR項目根目錄
    • REACT_ROOT_URL_FILES – 要通過根 url 提供的文件名列表(例如 /favicon.png)
    • STATICFILES_DIRS – 添加反應創建的靜態文件包的目錄
#settings.py

REACT_DIR = os.environ.get('REACT_DIR','/path/to/react/app/')
REACT_ROOT_URL_FILES = os.environ.get("REACT_ROOT_URL_FILES",'favicon.png manifest.json robots.txt').split(" ")

STATIC_URL = f'/{os.environ.get("STATIC_URL","static")}/'
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [
    #...
    os.path.join(REACT_DIR,'build','static')
]
  • 然后在views.py寫入視圖來處理反應根目錄文件(來自REACT_ROOT_URL_FILES的名稱)以及反應index.html
from django.views.generic import View
from django.http import HttpResponse,FileResponse
from django.conf import settings
import os


class ServeReactView(View):

    def get(self,request):
        try:
            url  = request.path.strip('/')
            if url in settings.REACT_ROOT_URL_FILES:
                #return one of the files named from the list
                file_name = url
                file = open(os.path.join(settings.REACT_DIR,'build',file_name),'rb')
                return FileResponse(file)

            with open(os.path.join(settings.REACT_DIR,'build','index.html')) as file:
                #return react index.html
                return HttpResponse(file.read())
        except:
            return HttpResponse(
            """
            {} not found!
            """.format(request.path),status=501)
  • 並在 並將此視圖添加到urls.py
#urls.py

urlpatterns = [
    #...
    re_path(r"^.*",ServeReactView.as_view(),name="serve_web_client_view")
]

PS當您提供更常見的反應文件(圖像等)時,我認為最好將它們放入public/static/ react 項目目錄中,因此它們將被移動到build/static並稍后用作其他靜態文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM