skip to Main Content

I’m trying to setup a development environment for React and Django.

https://github.com/axilaris/django-react <– Here is my project code for reference. You can easily run in with the instructions below easily.

Django (runs on port 8000)

cd backend <-- to to this directory
backend> python3 -m venv backendvirtualenv && source backendvirtualenv/bin/activate
backend> pip install -r requirements.txt
backend> python manage.py makemigrations
backend> python manage.py migrate
backend> python manage.py runserver

React (runs on port 3000)

cd frontend <-- to to this directory
frontend> npm install
frontend> npm run build
frontend> npm start

However, I’m trying to serve React staticfiles in Django so that I can run React on localhost:8000.

In settings file:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATICFILES_DIRS = [os.path.join(BASE_DIR, '../frontend/build/static')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

and the I run

backend> python manage.py collectstatic
backend> python manage.py runserver

However, when I point to my browser (http://localhost:8000/). It doesnt still have the React pages.

image description

How can I configure django so that I can run React and Django together in port 8000 ?

2

Answers


  1. Follow below procedure in the given order.

    • Open console

    • run python manage.py startapp frontend

    • go into frontend folder just created by above command and

      • create a file called urls.py
      • create a folder called templates
      • create a folder called static
    • add newly created frontend app to project settings.py(in installed apps, as normally do) ref

    • Move/copy your react app folder content to newly created templates folder and static folder

    • Open views.py and create index view ref – (Put index.js content in index.html and use django static template tag and put appropriate urls for app.js,app.css, index.css imports.)

    • Open urls.py and add index view ref

    • Open project urls.py and add empty path map to newly created index view ref

    Django is not a static server. Even if you could host it from static folder in development, in production it(static files) should be handled by CDN or nginx. Not django.

    This answer shows how to convert react app to django app.

    Login or Signup to reply.
  2. I think this is what you are looking for :
    https://fractalideas.com/blog/making-react-and-django-play-well-together-hybrid-app-model/

    It uses whitenoise and collectstatic

    The idea here is that you can build your React app, and once built, HTML is served as template by Django, and Whitenoise is used for the static files (js/css/svg etc)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search