如何使用reactjs在django url中获取url中的媒体图像

如何使用reactjs在django url中获取url中的媒体图像,django,reactjs,Django,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') url.py from django.contrib import admin from django.urls i

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')
url.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一起使用

我在react应用程序中给出了构建文件夹的路径,如下所示

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',
            ],
        },
    },
]
当我去路径获取图像时 在用户上传的side media文件夹中,我得到了react route页面。 我没有从媒体文件夹中获取图像

如何通过url查看媒体照片


我想我刚刚用Django后端+React前端的一个项目解决了这个问题。它在您的url模式中

据我所知,这是一种包罗万象的模式:

re_path('', TemplateView.as_view(template_name='index.html'))
基本上覆盖您编写的媒体url模式(以及它下面的任何其他模式),这会阻止Django后端允许您访问媒体文件。要解决这个问题,只需确保catch-all路由是模式上的最后一个路由。完成其余模式后,在新行上执行以下操作:

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

这样,您可以在所有其他路径之后将其添加到路径中,而不会“阻止”任何其他路径。希望这能解决它

伙计,你的解决办法是genus@soubhagya-普拉丹为你做了这件事?:)很好的解决方案,做了这样的事情,我认为这是错误的。现在我对你的解决方案很满意。天才。