0

I'm confused about serving media files on django and react. Here is my code:

Here is my 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')

urls.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)

Render it on react :

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

I put my image on build/img folder. When i open with localhost 3000 it's rendered but when i open with localhost 8000, i get not found error with this image link http://127.0.0.1:8000/img/logo.jpeg

My question is :

Where to put images? Should i create media folder to store all my image or put it on build/image folder? How to specify the src link to image on in react?

Thanks.

penk
  • 197
  • 1
  • 3
  • 14

2 Answers2

0

In your original config Django looking the files in media dir, not in build/img dir

Change media files settings from

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

To

If you are storing images inside the build/img folder as you mentioned in the comments then MEDIA_URL & MEDIA_ROOT should be like

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

Now you can use the access image files in This URL Pattern http://127.0.0.1:8000/img/logo.jpeg

Faisal Nazik
  • 2,367
  • 4
  • 17
  • 40
0

Answering:

  • Put react images into public/static react project directory, so they will be moved to build/static and later served as other static files
  • In react there is something called PUBLIC_LINK. I recommend to read this answer

I can propose more general approach for react+django in production:

  • In settings.py create 3 varibles:
    • REACT_DIR – for your react project root
    • REACT_ROOT_URL_FILES – list of filenames to be served via root url (e.g. /favicon.png)
    • STATICFILES_DIRS – add directory where react created static files bundles
#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')
]
  • Then in views.py write view to handle react root dir files (of names from REACT_ROOT_URL_FILES) as also react 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)
  • And at the and add this view to urls.py:
#urls.py

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

P.S When you're serving more common react files (images etc..) I think it's better to put them into public/static/ react project directory, so they will be moved to build/static and later served as other static files

mka
  • 153
  • 5