Deploy a Django app to PythonAnywhere for free.

SHAIK IRFANSHAIK IRFAN
6 min read

Introduction

Now that we have completed the development of our website, it’s time for the exciting part—deploying the code to a web server. Deploying a website can often be a complex and frustrating process, however, this is another area where Django makes the process of deploying a website easier.

Django will run on any server that supports Python’s Web Server Gateway Interface (WSGI). To run Django on a WSGI server only requires a single configuration file—wsgi.py.

Django by default supports the three most popular Internet databases— MySQL, PostgreSQL and Oracle – with many third-party interfaces to both SQL and non-SQL database engines.

What this means is that pretty much any host that either supports Python directly, or where you can set up your own virtual server (which is most cloud-based servers these days), will support Django.

In this Article, we will be using PythonAnywhere as they have a free beginner account that is perfect for demonstrating a live deployment without costing you any money.

I also chose PythonAnywhere because they have a deployment process that still requires you to do some setup. Many Django-friendly hosts now have “1-click” installs that, while convenient, don’t teach you the mechanics of deploying a website.

Prepare your project in local system

I assume you have Django project that is fully functioning in your local system. Make sure it is bug free by testing it using Django Development Server.

I assume the name of the project is website in c:\django folder. It has a single project called books that uses SQLite database. The following is the directory structure of website project. I am showing only important files in that project.

c:\django
      website
          manage.py
          db.sqlite3
          website
            settings.py
            ...
          books
            templates
            static
               styles.css 
            ...

In order to deploy a Django project to any production server, you have to take a few steps. Exact steps may differ from one server to another. Here I am taking steps needed for PythonAnywhere.com. However, most of the steps are to be taken even for other servers such as Heroku etc.

Change website\settings.py

Go to settings.py in website folder and make the following changes.

DEBUG = False
ALLOWED_HOSTS = ['localhost','Gabbar.pythonanywhere.com'] 
DATABASES = {
     'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': str(BASE_DIR / 'db.sqlite3'),# str must be used otherwise throws error 
    }
}
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')

Here are important changes:

  • Change DEBUG to False

  • Use str() in DATABASE NAME concatenation

  • Add Gabbar.pythonanywhere.com in ALLOWED_HOSTS

  • Specify which folder should contain static files using STATIC_ROOT

Collect static files into a folder

All static resources like images, stylesheets must be placed in a single folder in the server. So, we need to use collectstatic command to collect all static resources and place them in a folder, whose name is mentioned using STATIC_ROOT in settings.py.

Give the following command from outer website folder in which we have file manage.py. It will copy all static resources of all applications into the folder mentioned in settings.py - staticfiles.

python manage.py collectstatic

Create .zip file

Once settings.py is modified and static files are collected into a single folder, we are ready to create a .zip file that will be uploaded to PythonAnywhere.

However, it must be noted that it is possible to use git to clone a repo that is available in github.com. You can push your project (from local system) to Github repo and then clone it in PythonAnywhere.

I feel, to start with, it is easier to zip the entire project, upload to PythonAnywhere and unzip there. PythonAnywhere does allow you to upload individual files and even modify them there in the server using a simple editor.

Once website.zip (using any software like WinZip) is created for website folder, we are ready to upload to PythonAnywhere.

Deploy to PythonAnywhere

The first step in deploying the website is to set up your account with PythonAnywhere. Go to https://www.pythonanywhere.com and create your free beginner account. Once you have created your account and logged in, you will be directed to your dashboard.

At the top of your dashboard are five tabs—Consoles, Files, Web, Tasks and Databases. We will be visiting four of these tabs in turn to set up your website.

Upload zip file and unzip

Go to files section of PythonAnywhere and select Upload a file button. Select website.zip file from local file system to be uploaded.

You can see website.zip in your home directory (/home/Gabbar).

Go to bash console using Consoles option in Dashboard and select bash option.

Make sure you are in home directory and unzip website.zip.

~ $ pwd
/home/Gabbar
~ $ unzip website.zip
....
~ $ cd website
~/website $ ls
books  db.sqlite3  manage.py staticfiles  website

Now you see a folder /home/Gabbar/website with all files related to project.

Installing libraries

In case your project needs some extra libraries that PythonAnywhere is not providing by default, you can install them using pip3.

You can create a virtual environment also if you need a separate environment for your project.

Do check what libraries PythonAnywhere is providing (batteries included) before you manually install them.

If you decide to install any required library like Django Rest Framework, use PIP3 as follows. You must use --user flag otherwise it throws error.

~$pip3 install djangorestframework --user

Configure the Web App

From Dashboard in PythonAnywhere, click on Web link to go to web section.

Click on Add a new web app and it will ask you to provide details of web application.

In Select a Python Web Framework section, select Manual Configuration and then select Python 3.8 as your Python version.

When it displays configuration of your newly created web application, provide the following details:

Source code: /home/Gabbar/website
Working directory: /home/Gabbar/
WSGI configuration file:/var/www/Gabbar_pythonanywhere_com_wsgi.py

Click on WSGI configuration file and make the following changes:

# +++++++++++ DJANGO +++++++++++
# To use your own django app use code like this:
import os
import sys
#
## assuming your django settings file is at '/home/Gabbar/mysite/mysite/settings.py'
## and your manage.py is at '/home/Gabbar/mysite/manage.py'

path = '/home/Gabbar/website' 
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'website.settings' 
#
## then:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Go to Static files section and make the following changes:

URL            Directory    
/static/    /home/Gabbar/website/staticfiles
  • Go to top of the page and click on Reload Gabbar.pythonanywhere.com button.

  • Now click on Gabbar.pythonanywhere.com link provided above Reload button to test your web application. It must be successfully running.

Add a Home Page

If you tried to navigate to http://<yourusername>.pythonanywhere. com now you would get an error. This is because we have not added any pages to our new website. Go to http://<yourusername>.pythonanywhere.com/admin/, log in with the superuser account you created and add a home page:

Save the page and click on VIEW SITE from within the Django admin. If all has gone to plan, you should see your home page. Feel free to add more pages now if you like.

OK, we’re now ready to set the site into production mode. Before we go on, you’ll notice we have not configured a mail server so that our contact form can send emails, rather than dump the response to the console.

This is because you can’t set up a mail server on a free account and I wanted you to experience deploying a website without having to pay for hosting. I researched alternatives, but they were all too complicated for this introductory course. If you do want to dig deeper and set up an email server, there are plenty of resources that can be found online to assist. Just type in send email from Django for free into your favorite browser.

You now have a production-ready website deployed and ready to show to the world.


That's a wrap. Thanks for reading.

Hope this article was helpful to you.

If you enjoyed reading this, then please like and share this article with others.

Have fun coding!

0
Subscribe to my newsletter

Read articles from SHAIK IRFAN directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

SHAIK IRFAN
SHAIK IRFAN

"Full Stack Web Developer | Bridging Front-End Elegance with Back-End Power | Crafting Dynamic and User-Centric Digital Solutions"