簡體   English   中英

如何使用reactjs在django url中的url中獲取媒體圖像

[英]How to get media images in url in django url with reactjs

settings.py 中的靜態和媒體配置

STATIC_URL = '/static/'

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

MEDIA_URL='/media/'

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

網址.py

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('', TemplateView.as_view(template_name='index.html')),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

在這里,我將 Django 與 reactjs 一起使用。

我已經在這樣的反應應用程序中給出了構建文件夾的路徑。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'frontend','build')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

當我要去http://127.0.0.1:8000/media/images_OkG6q2k.jpeg路徑以獲取用戶上傳的側媒體文件夾中的圖像時,我正在獲取反應路線頁面。 我沒有從媒體文件夾中獲取圖像。

我如何通過網址查看媒體照片。

項目結構

當我訪問 url 時,react home 來了,而不是像這樣的媒體圖像

我想我剛剛用 Django 后端 + React 前端的一個項目克服了這個問題。 它在您的網址模式中。

據我了解,這種包羅萬象的模式:

re_path('', TemplateView.as_view(template_name='index.html'))

本質上覆蓋了您編寫的媒體 url 模式(以及它下面的任何其他模式),這會阻止 Django 后端允許您訪問媒體文件。 要解決此問題,只需確保所有路徑是您模式中的最后一個。 完成其余模式后,在新行上執行以下操作:

urlpatterns += [re_path('', TemplateView.as_view(template_name='index.html'))]

這樣,您將它添加到您的所有其他路徑之后,它不會“阻止”任何其他路徑。 希望這能解決它!

暫無
暫無

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

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