Reputation: 193
I am fairly new to React/Django/web development in general. I know there are a lot of questions on SO about how to load static files in Django templates, but I couldn't find anything helpful on how to do this in React components.
Scenario: I am building a React-Django app, and one of the features is to render a PDF document based on some user input. I am able to render the pdf successfully with react-pdf
if the file is stored somewhere in the react app's source tree.
However, I want to serve these pdf files from the backend. Currently, I have a Django model with a FilePathField
that points to where these pdfs are on my filesystem. What is the best practice for using this file path to render the pdf in React? Also, is this approach even correct?
Upvotes: 2
Views: 2344
Reputation: 193
I made it work under development settings. Here are the steps that I followed
First, in the project-level urls.py
, add staticfiles_urlpatterns
to urlpatterns
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('ml/', include('ml.urls'))
]
urlpatterns += staticfiles_urlpatterns()
Second, specify where your static files are in settings.py
. In my case, I put all of these files in the project-level assets
folder.
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets')
Finally, I just send the static URL as a response (e.g /static/assets/sample.pdf) to a react component that can render pdfs.
Would welcome any feedback in the comments. Thanks!
Upvotes: 3