Skip to main content

Setting up a Django Project for Production

We have a default application running at <username>.pythonanywhere.com. Now you will want to deploy your own application, instead of the one automatically generated by the PythonAnywhere wizard, to that domain. Once this is done, anyone having access to that URL will be able to use your Django web application. But befor that, you need to make some small changes to your project configuration.

note

The following changes to the project configuration will cause your application to not work correctly running the Django server locally (using python manage.py runserver). We will address that problem in the last section of this chapter.

We already talked about the DEBUG variable defined in settings.py, which indicates whether the project runs in debug mode (True) or not (False). We also saw that when the debug mode is active, Django relaxes some security policies: for example, it shows code excerpts when an exception occurs. These types of situations should be avoided in a production environment. Therefore, let's change

DEBUG = True

to

DEBUG = False

When debug mode is disabled, Django requires the list immediately below to be configured:

ALLOWED_HOSTS = []

Items of ALLOWED_HOSTS must indicate the IP addresses or domains in which the web application is served in the production environment.

note

The need to configure ALLOWED_HOSTS in production is a security policy. For this reason, Django will throw an error if you try to access an application with debug mode disabled and without populating ALLOWED_HOSTS. For more information about the vulnerability that this procedure neutralizes, see Host header validation in the Django documentation.

In our case, we will just put the subdomain that PythonAnywhere has created for us. For example:

ALLOWED_HOSTS = ["rpacc.pythonanywhere.com"]

(Remember to replace "rpacc" with your PythonAnywhere username.)

That's the essential requirement to run a Django application in production. We will change other settings in later sections.