Loading MEDIA_ROOT files with Django Webpack Loader

203 Views Asked by At

After I setup a vue frontend with a django webpack loader, the media files are not rendering.

settings.py

STATIC_URL = '/static/'
MEDIA_URL = "/media/"

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)


WEBPACK_LOADER = {
    "DEFAULT": {
        "BUNDLE_DIR_NAME": "dist/",
        "STATS_FILE": os.path.join(BASE_DIR, "frontend", "webpack-stats.json"),
    }
}

And urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include("companies.routes.urls")),
    path('api/v2/', include("projects.routes.urls")),

    path('accounts/register/', RegistrationView.as_view(
        form_class=CompanyUserForm,
        success_url="/",
    ), name="django_registration_register"),

    path('accounts/', include("django_registration.backends.one_step.urls")),
    path('accounts/', include("django.contrib.auth.urls")),
    path('api-auth/', include("rest_framework.urls")),
    path('api/rest_auth/', include("rest_auth.urls")),
    path('api/rest_auth/django_registration/', include("rest_auth.registration.urls")),

    re_path(r'^.*$', IndexTemplateView.as_view(), name="entry-point")
]

urlpatterns += [
    re_path(r'^media/(?P<path>.*)$', serve, {
        'document_root': settings.MEDIA_ROOT
    }),
]

# adding the media root path.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

But when I browse the media file url, image isn't rendering. The issue lies inside urlpatterns at this line re_path(r'^.*$', IndexTemplateView.as_view(), name="entry-point") when I comment out this part. I can see the image. But i need the re_path for the frontend view. How should fix this issue?

1

There are 1 best solutions below

2
On BEST ANSWER

you need to serve your media files add this to your urls.py

from django.views.static import serve

urlpatterns += [
    re_path(r'^media/(?P<path>.*)$', serve, {
        'document_root': settings.MEDIA_ROOT
    }),
]