Skip to content

Instantly share code, notes, and snippets.

Django and Create-React-App Integration
// The following instructions were tested on Windows, adjust it if you're running other OSs
## --- Create the python Virtual Environment --- ##
virtualenv mysite/venv
.\mysite\venv\Scripts\activate
## --- Install Django --- ##
pip install django
django-admin startproject mysite mysite
cd mysite
## --- Django App with a react frontend --- ##
python manage.py startapp myapp
cd myapp && mkdir templates && cd templates
## --- Install create-react-app --- ##
npm install create-react-app
## --- Create the frontend --- ##
create-react-app myapp
cd myapp
## --- Build the frontend to produce "index.html" and other "js", "css" files --- ##
npm run build
## --- add "myapp" to django settings --- ##
## --- Adjust INSTALLED_APPS in settings file --- ##
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # my custom app with a react frontend
]
## --- Adjust django static files directories, in settings file add at the end --- ##
REACT_APP_DIR = os.path.join(BASE_DIR, 'myapp/templates/myapp')
STATICFILES_DIRS = [
os.path.join(REACT_APP_DIR, 'build', 'static'),
]
## --- Add myapp urls (will be created shortley) to django project urls --- ##
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^', include('myapp.urls')),
url(r'^admin/', admin.site.urls),
]
## --- create the file "urls.py" inside "myapp" django app with the following content --- ##
from django.conf.urls import url
from .views import HomePage
urlpatterns = [
url(r'^', HomePage.as_view()),
]
## --- modify/create the file "views.py" inside "myapp" django app with the following content--- ##
from django.shortcuts import render
from django.views.generic import TemplateView
class HomePage(TemplateView):
def get(self, request, *args, **kwargs):
return render(request, "myapp/build/index.html", {})
## --- start your django server from project root --- ##
python manage.py runserver
## --- Open your browser to the URL --- ##
http://127.0.0.1:8000/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment