The video mentions copying code from the screen or transcript. This is a reference to the old, paid version of the course. I have now collated all the code together in one place in the source, which you can download here.
Deploying a Django Website
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 module, 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.
Preparing the Site for Deployment
Before we transfer the site files to the web server, we need to do some tidying up of the files in our project folders.
At this point, you can make a backup of your site files and work directly in your project folders, however, as I like to leave the local copy intact and running in case I need to troubleshoot, we will work with a zip file that will be uploaded to PythonAnywhere.
Navigate to the \mfdw_project folder and zip up the \mfdw_root folder. Your project tree should look like this when you are done:
Now, open the zip file to edit the contents (don’t extract!) and do the following:
1. Delete the db.sqlite3 file from inside the \mfdw_root folder
2. Delete the \uploads folder from inside the \mfdw_root folder
3. Delete all files inside \quotes\migrations folder
4. Delete all files inside \pages\migrations folder
5. Save and close the zip file
The purpose of this tidy up is to remove the test database and delete all old migrations so we can generate a clean set of migrations to apply to our new MySQL database on the web server.
We’re now ready to deploy our website to PythonAnywhere. In the next lesson, we’re going to set up our account with PythonAnywhere and upload our site files.
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.
Add a Database
First, we’re going to add a database. PythonAnywhere only provides the option to set up a MySQL database on a beginner account, so click on the Databases tab and scroll down to the Create a database section, enter mfdw_db as the database name and click Create.
You also need to create a password for your database, so scroll down a bit further and create a password for your new database .
Once you have set a new database password, write down the database host address (under Connecting: at the top of the Databases page), your username and the database name (if you didn’t use mfdw_db). You will need them in the next lesson.
Upload the Site Files
Next, we need to upload your site files to the server. Click on the Files tab in your dashboard and click on the Upload a file button and upload your zip file to the server. Once the zip file is uploaded, it will appear in your Files list.
To extract the site files, we need to open a console and run the unzip tool. PythonAnywhere has a few ways to open a console, but the easiest for this exercise is to click the “Open Bash console here” link at the top of the Files page.
PythonAnywhere will open a new console window that looks like the Windows terminal or PowerShell window you are used to. At the command prompt, type:
$ unzip mfdw_root.zip
If all has gone to plan, you will get a string of listings scrolling up the page as PythonAnywhere unzips your files to the server.
Next, we need to install django, but as we’re running our website inside a virtual environment, first we must install the virtual environment. Using the same console you opened in the last section, enter the following:
(env_mfdw) [timestamp] ~ $
The [timestamp] will show the current server time. Now it’s time to install Django into the virtual environment. Type the following at the command prompt and hit enter:
As we are using a virtual environment, we also need to install the Python database client for MySQL, We do that by typing pip install mysqlclient while we are still in the console and hitting enter.
Now that we have our account setup and have uploaded our site files and installed Django, in the next lesson we’re going to install and configure our Django project.
Install the Web App
Our site files have been uploaded and our Django app is installed. Now it’s time to install and configure the web app.
Return to the dashboard, click on the Web tab and then click Add a new web app. A series of windows will open prompting you for more information:
1. Click Next
2. Select Manual configuration. (DON’T select Django!)
3. Select Python 3.6
4. Click Next
PythonAnywhere will then create the new app for you. When the page refreshes, scroll down to the Virtualenv: section and click on “Enter path to a virtualenv, if desired” link. You will be prompted to enter a path to your virtual environment. Enter env_mfdw into the box and click the check button. PythonAnywhere will replace it with the full path to your virtual environment.
Configure the Web App
Now the web app is installed, we need to configure the WSGI file and Django’s settings to run on the web host.
While still on the Web tab, scroll down to the Code: section and open the wsgi.py file. Note that this isn’t the wsgi.py file from your project—the PythonAnywhere server ignores that file.
PythonAnywhere will open the file in an editor in your browser. There is a lot of stuff in here we don’t need. Delete everything in the file except the ++ DJANGO ++ section and then uncomment the relevant sections.
You also need to add your project path and add your settings module to the file. Carefully check your file against the screenshot. I have also put a copy of the file in the transcript
Make sure you save the file after you make the changes.
Return to the dashboard and select the Files tab. Navigate to your mfdw_site directory and open your settings.py file. There are three changes we need to make. You can pause the video as you go and make the changes, or copy them from the transcript.
First, we need to add our new site to the allowed hosts setting
The we need to add the database configuration settings. The changes to the database connection settings are straight forward, just enter the settings I suggested you write down earlier in the module. If you forgot to write down the settings, open your Databases tab in a new window and copy and paste the settings into the file.
Finally, we need to add the path to our static root folder. The STATIC_ROOT path provides the necessary path statement for the collectstatic management tool we will be using shortly.
Run Django Management Commands
With the web app installed and configured, now we have a few Django management commands to run.
Return to the Web tab, scroll down to Virtualenv: and click on the “Start a console in this virtualenv” link. When the virtual environment is running in the console, change into the mfdw_root folder.
Once in the root folder, we need to make and run the migrations to set our models up in the database. First, we tell Django to create new initial migrations for our pages and quotes apps:
$ python manage.py makemigrations pages quotes
Then we run all migrations:
$ python manage.py migrate
You can ignore the warning message if it appears. PythonAnywhere creates a default database for you when you create your account. If you don’t delete the default database, you will get this warning message. As it’s not related to our database, we can ignore it.
Add a Superuser
Our new database needs an admin user, so create one using the createsuperuser command we used in Module 2:
$ python manage.py createsuperuser
Add the Static Files
$ python manage.py collectstatic
To link our project to the Static Files, we need to exit the console and return to the Web tab on the PythonAnywhere dashboard.
Scroll down to the Static files: section and add your STATIC_URL (/static/)
And add the same path as you entered in settings.py
When you have entered your static files setting correctly, your Static files:
should look like this.
Once you have saved the static files setting, scroll back to the top of the page and click on the big green Reload button.
The site is now setup and configured and ready for go-live. In the next lesson we’re going to add some content and switch the site from development to production.
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.
Set Site to Production Mode
The final, but most important task to complete is to secure your site for production use. This requires two changes to your settings.py file:
1. Generate a new secret key; and
2. Set debug mode to False.
Before we go and edit our settings file, let’s generate a new secret key. The simplest way to do this is to run the virtual environment we used for developing the website on your local machine and create a dummy project:
Remember, you’re running this on your local machine, not inside PythonAnywhere.
Once the dummy project has been created, you can simply copy the secret key from the settings file, and add to your production file, then delete the dummy project.
Another way to generate a new secret key is to generate it manually using the same code that Django uses internally to generate secret keys. From within a standard Python shell, enter the following. Pause the video and type into your editor, or copy from the transcript:
The last line is the generated secret key. It will be different every time you run the code.
Once you have generated a new secret key, return to the PythonAnywhere dashboard and select the Files tab. Navigate to your my_site directory, open your settings.py file and paste your new secret key into the file.
After you have added the new key, change DEBUG to False, save the file and you are done.
You now have a production-ready website deployed and ready to show to the world.
That’s it for the course too – you are officially a Django programmer!
Of course, there is a lot more to mastering Django, but I sincerely hope that this beginner’s course has given you enough of a foundation in Django programming to be able to build on your skills and put you well on the path to becoming a professional Django programmer.
Don’t forget to check out the many Django resources I have linked to in the resources section.
One more thing before you go – please don’t forget to fill out the exit survey before you go. It’s your feedback that allows me to keep improving the course.
All the best with your programming journey and I hope have a great day.
Like the Content? Grab the Book for as Little as $5!
Other than providing you with a convenient resource you can print out, or load up on your device, buying the book also helps support this site.
eBook bundle includes PDF, ePub and source and you only pay what you can afford.
You can get the paperback from Amazon.