Building a good working environment is very important for your productivity. Maybe it takes a while to configure, but when it’s well done it’s worth the time!
For example, virtual environments help you have your packages organized and controlled, and a good text editor helps you with variable names, package methods, and syntax highlighting.
Oh, and If you didn’t read the introduction, this Django tutorial is up-to-date. We will use Django 1.8 and Python 3. This doesn’t mean you can’t follow the tutorial if you are using an older version 😉 It only means that you will have to work harder in your debugging, to solve problems I can’t anticipate here.
The guideline of this post is:
- Building your Working environment
- Install Django 1.8
- Working directory and Sublime Text
- Obey the Testing Goat
- Create a Django project
- Start a development server
Building your Working environment
To follow this Django tutorial you will need Python3, the package manager pip3 and the following packages: virtualenv and virtualenvwrapper.
If you’re using Mac OS X you can check this post:
Install Python 3 on Mac OS X and use virtualenv and virtualenvwrapper
You will also need a nice text editor to manage all the Django files we will create. I recommend Sublime Text but if you feel comfortable with another text editor go ahead! Check here on how to install and configure Sublime Text 3 for Django.
Although we will talk about this in the next post, we will need Git, the package control system. If more than one users will be managing the code, I recommend you use a Git repository like GitHub or Bitbucket (the last one offers private repositories for free accounts). You can learn the basis about Git on this Git Tutorial.
Ok, now we are ready to start with our super-cool Django project 😉
Install Django 1.8
First, we will create a virtual environment with Python3 as the default Python. In your terminal, type:
$ which python3
to know your python3 path. In my case it was /usr/local/bin/python3. Next, create a virtual environment to use for development, and specify Python3 as the default Python (remember that with virtualenvwrapper the virtual environments are created in the default folder ~/.virtualenvs, regardless of the working folder):
$ mkvirtualenv --python=/usr/local/bin/python3 tb_dev
Change your python path if its different than mine, and also change the name of the virtual environemnent tb_dev if you like. You’ll see that this virtual environment is now active — the command shell will have something like (tb_dev)[user@host]$.
You can deactivate the virtual environment with
$ deactivate
and activate it again with
$ workon tb_dev
Note that if you are working in this environment, when you type python you are activating python3, and when you call pip, you are calling the python3 version, pip3. Cool!
Ready to install the latest version of Django?! With the tb_dev active, type:
$ pip install Django==1.8.5
Note: you can check if there is a new version available here.
Working directory and Sublime Text
Create a new folder in your computer, named taskbuster_project:
$ mkdir taskbuster_project
This folder will be the top folder containing your Django project, all its documentation, deployment files, version control files, sublime project files, functional tests, etc.
Let’s create a Sublime Text project to manage all the files inside this folder (or with your preferred editor). Here, I will assume that you have activated the subl command to open files using the terminal:
$ subl taskbuster_project
This command will open all the files inside the tastbuster_project folder. Next, go to the top menu and select Project / Save Project As, name your project as TaskBuster.sublime-project, and save the file inside the same taskbuster_project folder (by default is its top folder).
Now, you’ll see two different files inside the taskbuster_project: TaskBuster.sublime-project and TaskBuster.sublime-workspace (Note: the last one is not visible in the Sublime editor, but it is on the terminal).
Obey the testing Goat
I am reading an incredible book: Test-Driven development with Python, by Harry J.W. Percival. And it says that you must obey the Testing Goat — a little voice in your head that tells you to write a test before writing any code. Test first, test first!
And this is what we will do here, before creating any Django project…
We know that when we create successfully a Django project, we get the usual It worked! Django blue page when we go to the localhost http://127.0.0.1:8000. If we inspect this page, we will see that in its head section, the title tag is<title>Welcome to Django</title> I know, you can’t see that because you haven’t created any project yet! You will have to trust me for now 😉
So let’s write a test that asserts than when we go to http://127.0.0.1:8000 we get a page with Welcome to Django in its title. Of course, this test will fail, because we don’t have any project defined yet! But that’s what’s all about: create your test first, and then the code.
First, we will create another virtual environment for testing, with Django 1.8 in it:
$ mkvirtualenv --python=/usr/local/bin/python3 tb_test $ pip install Django==1.8
Next, in order to simulate a browser for our testing, we will use the Selenium package (before installing it you will need to have Firefox):
$ pip install --upgrade selenium
Go inside the taskbuster_project folder and create a folder for the functional tests. This folder will contain all the files that test the project functionality from the user point of view. Create also the file all_users.py in it:
$ cd taskbuster_project $ mkdir functional_tests $ cd functional_tests $ touch all_users.py
Edit this file with your editor and write:
# -*- coding: utf-8 -*- from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_it_worked(self): self.browser.get('http://localhost:8000') self.assertIn('Welcome to Django', self.browser.title) if __name__ == '__main__': unittest.main(warnings='ignore')
Let’s analyze the previous code step by step:
- The first line indicates the coding of the file
- Then, it imports selenium and unittest, a Python library for testing
- It creates a TestCase class, named NewVisitorTest, with:
- a setUp method that initializes the test. It opens the browser and it waits for 3 seconds if needs to (if the page is not loaded).
- a tearDown method that runs after each test. It closes the browser.
- a method that starts with test and that asserts that the title of the webpage has Welcome to Django in it.
- The setUp and tearDown methods run at the beginning and at the end of each test method (the ones that start with the word test).
- The final lines mean that only if Python runs the file directly (not imported) it will execute the function unittest.main(). This function launches the unittest Test runner, that identifies the different tests defined by looking for methods that start with test.
- We call the unittest.main() function with the optional parameter warnings=’ignore’ to avoid a ResourceWarning message.
Let’s run this script with
$ python all_users.py
The resulting output shows how the test, obviously, fails. You will see something like
FAIL: test_it_worked (__main__.NewVisitorTest)
and an AssertionError with the message Welcome to Django not found.
So let’s create a Django project and make this test pass!
Create a Django project
Get inside the taskbuster_project folder and type:
$ django-admin.py startproject taskbuster .
Note the dot at the end of the command, this will create the project taskbuster without creating any additional folders. The current structure of your top folder should be:
Note: this picture shows the output of my terminal when using the tree command (if you want to use it, you may have to install it first).
As you can see, we have created:
- the manage.py file, used to manage the development server, database migrations, custom scripts, etc.
- the taskbuster folder, which contains:
- __init__.py file indicating that this folder is a Python package
- settings.py file, used to configure the project
- urls.py, used to relate urls with views
- and the wsgi.py file, used to configure Django’s deployment.
Later in this tutorial, you will see that the taskbuster folder will also contain all our apps, templates, static files and other files related to our project.
Start a development server
Once we have the project created, we can start the development server. Open a tab in your terminal with the tb_dev environment activated, go inside the taskbuster_project folder and run
$ python manage.py runserver
You might see a warning about migrations, but don’t worry, we’ll get to that latter in this tutorial. At the end of the output you might see something like
Starting development server at http://127.0.0.1:8000/.
You can open a browser and check this url to see the It worked Django message, but I rather prefer to use the test we have created 🙂
Open another terminal tab (with ctrl+t or cmd+t) and activate the tb_test envrironment. Now, let’s run our test:
$ python functional_tests/all_users.py
And now you should see the message:
Ran 1 test in 0.05s OK
indicating that your test passed! 🙂
Now it would be a good moment to start a Git repository and start the version control of your code. However, before going into that we need to talk about Security. We want to keep the Secret Keys out of the version control, to maintain them… Secret!
And you will learn how to do that on the next part of the tutorial, Settings files and Version control
Don’t miss it! 😉
Please help me and share it to your friends, they might find it useful too! 😉