This guide will help you setup a Django app to use React.js via templates and deploy to AWS using their Elastic Beanstalk service.
- Follow prerequisites from http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html
virtualenv eb-virtsource eb-virt/bin/activate
pip install -r requirements.txt
django-admin startproject [PROJECT NAME]python [PROJECT NAME]/manage.py migrate
- Run
django-admin.py startapp [APP NAME]inside yourDJANGO PROJECT FOLDER - Add app to
settings.pyin theINSTALLED_APPSsection as[DJANGO PROJECT NAME].[APP NAME],
-
Create
staticandtemplatesfolder inside theDJANGO PROJECT FOLDER(same level asDJANGO APP) -
Change the
DIRSproperty of theTEMPLATESvariable to be
'DIRS': [os.path.join(BASE_DIR, '[DJANGO PROJECT NAME]/templates')],
- Add this underneath the
TEMPLATESvariable:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '[DJANGO PROJECT NAME]/static'),
]
- Add this on top of the
STATIC_URLvariable:
STATIC_ROOT = os.path.join(BASE_DIR, "..", "www", "static")
Paste the code below in your settings.py file to use AWS S3 to store static files (such as images)
AWS_STORAGE_BUCKET_NAME = '[YOUR S3 BUCKET NAME]'
MEDIA_URL = 'http://%s.s3.amazonaws.com/uploads/' % AWS_STORAGE_BUCKET_NAME
DEFAULT_FILE_STORAGE = "storages.backends.s3boto.S3BotoStorage"
Change ALLOWED_HOSTS to
ALLOWED_HOSTS = ['localhost', '.elasticbeanstalk.com']
- Install AWS command-line client using
pip install awscliinside your virtual env- If you encounter problems with installing this, try running
pip install awscli --userinstead
- If you encounter problems with installing this, try running
- Install eb tools using
pip install --upgrade awsebcli - Make the following changes to your
settings.pyfile:
- Replace the
DATABASESvariable with:
if 'RDS_DB_NAME' in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['RDS_DB_NAME'],
'USER': os.environ['RDS_USERNAME'],
'PASSWORD': os.environ['RDS_PASSWORD'],
'HOST': os.environ['RDS_HOSTNAME'],
'PORT': os.environ['RDS_PORT'],
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '[LOCAL DATABASE NAME]',
'USER': '[LOCAL DATABASE USER]',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '5432',
}
}
This above code checks the environment variables to see if it is local or production. If it is not the local environment then it will use the AWS RDS variables to connect to the production database instead of the local database.
NOTE: You'll have to download Postgres and create the local database yourself via commandline
- Copy this code below the code from the step above
# AWS EB Settings
AWS_QUERYSTRING_AUTH = False
AWS_ACCESS_KEY_ID = '[YOUR AWS ACCESS KEY ID]'
AWS_SECRET_ACCESS_KEY = '[YOUR AWS SECRET ACCESS KEY]'
-
Initialize your EB environment using
eb init -p python2.7 [PROJECT NAME] -
Create your EB environment using
eb create eb-virt(this will launch and create your elastic beanstalk environment)- If you get an error like
Error: pg_config executable not foundin youreb logsthen:
- If you get an error like
-
STILL IN PROGRESS
- Move
reactjs.zipinside yourDJANGO PROJECT FOLDERso the path looks like[DJANGO PROJECT FOLDER]/reactjs.zip - Unzip the
reactjs.zipfile and then delete it - Move all contents from inside the
reactjsfolder to the outside- For example:
reactjsfolder,fabfile.py, and the variouswebpackfiles should all be on the same level with yourDJANGO PROJECT FOLDER
- For example:
- In the same level as the
reactjsfolder, create a file called.babelrcwhose contents are:
{
"presets": ["es2015", "react", "stage-0"],
"plugins": [
["transform-decorators-legacy"],
]
}
-
In
fabfile.py,package.json,webpack.base.config.jsandwebpack.prod.config.js, change the[YOUR DJANGO APP NAME]placeholders to yourDJANGO PROJECT NAME- NOTE: change the output path in
webpack configfiles to be./[DJANGO PROJECT NAME]/static/bundles/prod/instead of it containing anyDJANGO PROJECTspecific folder names
- NOTE: change the output path in
-
Run
cd [DJANGO PROJECT NAME]and then runnpm ito install the node modules
Add this to your settings.py
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/local/', # end with slash
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-local.json'),
}
}
Add this to INSTALLED_APPS: 'webpack_loader',
To use React inside Django templates you have to do something like this (example):
{% load render_bundle from webpack_loader %}
<div id="App"></div>
{% render_bundle 'vendors' %}
{% render_bundle 'App' %}
The parts of the example above that will be different for you will be:
<div id="App"></div> and {% render_bundle 'App' %}.
If you check your webpack.base.config.js file, you will see that module.exports has an object called entry. This object specifies what React component(s)/container(s) will have bundles created for them.
These React component(s)/container(s) are the top-most and almost all other React components/containers will be their children. You can have multiple different entry points thus, separating your React code into multiple different bundles that you are free to use in whichever Django template you like.
Since we have an App.jsx file in our reactjs folder, we have created an entry point called App. We use {% render_bundle 'App' %} to use the bundle specifically generated for App.
- Replace placeholder with your
DJANGO PROJECT NAMEin.gitignoreto ignore thenode_modulesfolder
- http://www.trysudo.com/deploying-django-app-on-aws-using-elastic-beanstalk/
- http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html
sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
lcms2-devel libwebp-devel tcl-devel tk-devel
-
Move
requirements.txtinside the outerDJANGO PROJECT FOLDER(so it is on the same level as themanage.py -
Create
Procfilewith the following contents:
web: gunicorn {{ project_name }}.wsgi
-
Initialize
.giton the same level asmanage.py -
Create local database by logging into Postgres and running
CREATE DATABASE [NAME]; -
Followed https://github.com/SamSamskies/django-webpack-heroku-example
-
Add Postgres add-on for Django by running
heroku addons:create heroku-postgresql:hobby-dev -
Install the necessary
pythonlibraries:pip install dj-database-url pip freeze > requirements.txt -
Change your
settings.pyfile:import dj_database_url DATABASES['default'] = dj_database_url.config()