I’m starting today a new tutorial series about the Django fundamentals. It’s a complete beginner’s guide to start learning Django. The material is divided in 7 parts. We’re going to explore all the basic concepts in great detail, from installation, preparation of the development environment, models, views, templates, urls to more advanced topics such as migrations, testing and deployment.
I wanted to do something different. A tutorial that would be easy to follow, informative and fun to read. That was when I came up with the idea to create some comics along the text to illustrate some concepts and scenarios. I hope you enjoy the reading!
But before we start
Back when I worked as a substitute professor in a university, I used to teach a introduction to web development discipline for the newcomer students in the Computer Science course. And I would always start a new classes with this Confucius quote:
So, hands on! Don’t just read the tutorials. Let’s do it together! You will learn much more by doing and practicing.
The first thing we need to do is install some programs in our machine so to be able to start playing with Django. The basic setup consists of installingPython,VirtualenvandDjango.
Using virtual environments is not mandatory, but it’s highly recommended. If you are just getting started, it’s better to start with the right foot.
When developing Web sites or Web projects with Django, it’s very common to have to install external libraries to support the development. Using virtual environments, each project you develop will have its own isolated environment. So the dependencies won’t clash. It also allow you to maintain in your local machine projects that runs on different Django versions.
It’s very straightforward to use it, you will see!
First thing we want to do is install the latest Python distribution, which isPython 3.6.2. At least it was, by the time I was writing this tutorial. If there’s a newer version out there, go with it. The next steps should remain more or less the same.
We are going to use Python 3 because the most important Python libraries have already been ported to Python 3 and also the next major Django version (2.x) won’t support Python 2 anymore. So Python 3 is the way to go.
The best way to go is withHomebrew. If you don’t have it installed in your Mac yet, run the following command in theTerminal:
If you don’t have theCommand Line Toolsinstalled, the Homebrew installation might take a little bit longer. But it will take care of everything for you, so no worries. Just sit back and wait until the installation completes.
You will know when the installation completes when you see the following message:
==> Installation successful!
==> Homebrew has enabled anonymous aggregate user behaviour analytics.
Read the analytics documentation (and how to opt-out) here:
==> Next steps:
brew helpto get started
- Further documentation:
To install Python 3, run the command below:
Since macOS already ships with Python 2 installed, after you install Python 3, you will have both versions available.
To run Python 2, simply execute
pythonin the Terminal. For Python 3, use
We can test the installation by typing in the Terminal:
Go towww.python.orgclick on the Python 3.6.2 download page, scroll down until you see the download files listed below:
Pick the right version accordingly to your Windows distribution. If you are not sure which one is the right for you, the chances are you want to download theWindows x86-64 executable installerversion.
Go the your Downloads directory, right click on the installer and click onRun as administrator.
Make sure you check the optionAdd Python 3.6 to PATHand click on theInstall Nowoption.
After the installation completes, you should see the following screen:
Now search for theCommand Promptprogram and open it:
To test if everything is working fine so far, type following command:
As an output you should see:
For this tutorial I will be using Ubuntu 16.04 as example. Ubuntu 16.04 already comes with both Python 2 (available as
python) and Python 3 (available as
python3) installed. We can test the installation by opening theTerminaland checking the versions:
So all we have to do is install a newer Python 3 version. But we don’t want to mess with the current Python 3.5.2, as the OS makes use of it. We’re simply going to install Python 3.6.2 under the name
python3.6and let the older version be.
If you are using Ubuntu 16.04 or an older version, first add the following repository:
If you are using Ubuntu 16.10, 17.04 or 17.10 you don’t need to perform the step above.
Now everyone execute the following commands to install the latest Python 3 distribution:
The new installation will be available under
python3.6, which is totally fine:
Great, Python is up and running. Next step: Virtual Environments!
For the next step we are going to usepip, a tool to manage and install Python packages, to installvirtualenv.
Note that Homebrew already installedpipfor you under the name
pip3for your Python 3.6.2 installation.
In the Terminal, execute the command below:
In the Command Prompt, execute the command below:
First let’s installpipfor our Python 3.6.2 version:
Now we can installvirtualenv:
So far the installations that we performed was system-wide. From now on, everything we install, including Django itself, will be installed inside a Virtual Environment.
Think of it like that: for each Django project you start, you will first create a Virtual Environment for it. It’s like having a sandbox for each Django project. So you can play around, install packages, uninstall packages without breaking anything.
I like to create a folder namedDevelopmentin my personal computer. Then I use it to organize all my projects and websites. But you can follow the next steps creating the directories wherever it feels right for you.
Usually I start by creating a new folder with the project name inside myDevelopmentfolder. Since this is going to be our very first project, we don’t need to pick a fancy name or anything. For now, we can call itmyproject.
This folder is the higher level directory that will store all the files and things related to our Django project, including its own virtual environment.
So let’s start by creating our very first virtual environment and actually installing Django.
Our virtual environment is created. Now before we start using it, we need to activate:
You will know it worked if you see(venv)in front of command line, like this:
Let’s try to understand what happened here. We created a special folder namedvenv. It basically contains a copy of Python inside this folder. After we activated thevenvenvironment, when we run the
pythoncommand, it will use our local copy, stored insidevenv, instead of the other one we installed earlier.
Another important thing is that thepipprogram is already installed as well, and when we use it to install a Python package, like Django, it will be installed_inside_thevenvenvironment.
Note that when we have thevenvactivated, we will use the command
python3) to refer to Python 3.6.2, and just
pip3) to install packages.
Note that when we have thevenvactivated, we will use the command
python3.6) to refer to Python 3.6.2, and just
pip3.6) to install packages.
By the way, to deactivate thevenvsimply run the command below:
But let’s keep it activated for the next steps.
It’s very straightforward. Now that we have thevenvactivated, run the following command to install Django:
We are all set up now!
To start a new Django project, run the command below:
The command-line utilitydjango-adminis automatically installed with Django.
After we run the command above, it will generate the base folder structure for a Django project.
Right now, ourmyprojectdirectory looks like this:
Our initial project structure is composed by five files:
: a shortcut to use the
command-line utility. It’s used to run management commands related to our project. We will use it to run the development server, run tests, create migrations and much more.
: this empty file tells Python that this folder is a Python package.
: this file contains all the project’s configuration. We will refer to this file all the time!
: this file is responsible for mapping the routes and paths in our project. For example, if you want to show something in the url
, you have to map it here first.
: this file is a simple gateway interface used for deployment. You don’t have to bother about it. Just let it be for now.
Django comes with a simple web server installed. It’s very convenient during the development, so we don’t have to install anything else to run the project locally. We can test it by executing the command:
For now you can ignore the migration errors, we will get to that later.
Now open the following url in a Web browser:http://127.0.0.1:8000and you should see the following page:
Hit Control + C to stop the development server.
Hit CTRL + BREAK to stop the development server.
Hit Control + C to stop the development server.
In the Django philosophy we have two important concepts:
: is a Web application that does something. An app usually is composed by a set of models (database tables), views, templates, tests.
: is a collection of configurations and apps. One project can be composed by multiple apps, or a single app.
It’s important to note that you can’t run a Djangoappwithout aproject. Simple websites like a blog can be written entirely inside a single app, which could be namedblogorweblogfor example.
It’s a way to organize the source code. In the beginning it’s not very trivial to determine what is an app or what is not. How to organize the code and so on. But don’t worry much about that right now! Let’s first get comfortable with Django’s API and the fundamentals.
Alright! So, to illustrate let’s create a simple Web Forum or Discussion Board. To create our first app, go to the directory where themanage.pyfile is and execute the following command:
Notice that we used the commandstartappthis time.
This will give us the following directory structure:
So, let’s first explore what each file does:
: here Django store some files to keep track of the changes you create in the
file, so to keep the database and the
: this is a configuration file for a built-in Django app called
: this is a configuration file of the app itself.
: here is where we define the entities of our Web application. The models are translated automatically by Django into database tables.
: this file is used to write unit tests for the app.
: this is the file where we handle the request/response cycle of our Web application.
Now that we created our first app, let’s configure our project to actually_use_it.
To do that, open thesettings.pyand try to find the
We will explore those apps as we progress in this tutorial series. But for now, let them be and just add ourboardsapp to the list of
Using the analogy of the square and circles from the previous comic, the yellow circle would be ourboardsapp, and thedjango.contrib.admin,django.contrib.auth, etc, would be the red circles.
Let’s write our firstview. We will explore it in great detail on the next tutorial. But for now, let’s just experiment how it looks like to create a new page with Django.
Open theviews.pyfile inside theboardsapp, and add the following code:
Basically views are Python functions that receive an
HttpRequestobject, and returns an
HttpResponseobject. Receive a_request_as parameter, returns a_response_as result. That’s the flow you have to keep in mind!
So, here we defined a simple view calledhomewhich simply returns a message sayingHello, World!.
Now we have to tell Django_when_to serve this view. It’s done inside theurls.pyfile:
If you compare the snippet above with your ownurls.pyfile, you will notice I added the following new line:
url(r'^$', views.home)and important theviewsmodule from our appboardsusing
from boards import views.
As I mentioned before, we will explore those concepts in great detail later on.
But for now, Django works withregexto match the requested URL. For ourhomeview, I’m using the
^$regex, which will match an empty path, which is the homepage (this url:http://127.0.0.1:8000). If I wanted to match the URLhttp://127.0.0.1:8000/homepage/, my url would be:
Let’s see what happen:
In a Web browser, open the http://127.0.0.1:8000 URL:
That’s it! You just created your very first view.
This was the first part of this tutorial series. In this tutorial we learned how to install the latest Python version and how to setup the development environment. We also had a introduction to virtual environments and started our very first Django project and already created our initial app.
I hope you enjoyed the first part! The second part is coming out next week, on Sep 11, 2017. It’s going to be about models, views, templates and urls. We will explore together all the Django fundamentals! If you would like to get notified when the second part is out, you cansubscribe to our mailing list.
Just so we can stay on the same page, I made the source code available on GitHub.
The code is inside the folderpart-1.