Python for Django Programmers – Part 1

To gain a thorough understanding of Django, it’s important to have a good grounding in writing Python code. In part 1 of this Python primer tutorial, I will be explaining how Python code is structured and how to use the Python interactive interpreter in your Django development.

This post is an extract from my new book – Build Your First Website with Python and Django.

For your chance to join the launch team and get a 50% discount when the book is launched, see the end of this post.

Python Basics

In this chapter we are going to be spending a bit of time learning the basics of Python. This book is written for beginners who don’t have any knowledge of Python or Django. If you have some basic programming knowledge of Python, feel free to skip to the next chapter.

It might seem strange that the first bit of real coding we do in a Django book is in Python, but given that Django is written in Python, it makes perfect sense – if you understand the basics of Python, you will be able to understand Django in a much more comprehensive way. For example, by having a greater understanding of Python, you will be able to more quickly identify the bits of Django that are “plain Python” and the bits that are unique to Django.

Code Layout – Readability Counts

One of the founding principles that drove the design of Python was that code is read much more often than it’s written. Once a piece of code is written it may pass through many hands; read by other developers, documentation authors, auditors and testers. Experienced programmers will also tell you that being able to understand your own code, many months or even years after you wrote it, is extremely important.

Under this guiding principle, Python was designed to mimic natural written English as much as possible. One of these design choices was to use whitespace as a delimiter, rather than braces ({}), or BEGIN\END type statements used by other languages.

A delimiter is something that defines the beginning or the end of a block of text that belongs together. Consider the following:

# Kate's Awesome Nachos

1. Collect Ingredients:
    a. Large bag of corn chips
    b. Can of refried beans (preferably chilli)
    c. Jar of salsa (not hot!)
    d. Grated cheese
    e. Guacamole
2. Prepare Nachos:
    a. Tip bag of corn chips in oven dish
    b. Spread refried beans over corn chips
    c. Pour on jar of salsa
    d. Top with cheese
3. Cook in oven for 20 mins
4. Serve with guacamole

We can easily understand each step of this simple (but delicious!) recipe because it’s formatted in a way that all English speakers can understand – relevant information is grouped together in sentences and paragraphs and indentation is used so we can differentiate between the steps of collection of ingredients and preparation of the nachos.

Python treats whitespace in exactly the same way, for example the ingredients written as a Python list may look like:

ingredients = [
    "corn chips",
    "refried beans",
    "salsa",
    "grated cheese",
    "guacamole
]

You will notice that Python lists use brackets ([]) as a delimiter, with the indentation and surrounding whitespace clearly differentiation where the list starts and ends. (More on lists shortly.)

Functions for preparing and cooking the nachos might be written like this:

def prepare_nachos(ingredients):
    nachos = ""
    for ingredient in ingredients[:4]:
        nachos+=ingredient
    cook_nachos(nachos)

def cook_nachos(nachos):
    # cook in oven for 20mins

Now, this is a rather silly example, but I bet that you found it pretty easy to follow – even without quite understanding Python syntax. Our list of ingredients is broken up into one ingredient per line to create our ingredients list and we have used indentation to differentiate between the two Python functions (prepare_nachos and cook_nachos), and the code that belongs to each function.

Here are some real examples that you will see later in the book:

# A list from the settings.py file:

INSTALLED_APPS = [
    'pages.apps.PagesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

# A function from views.py

def index(request, pagename):
    if pagename == '': pagename = '/'
    pg = Page.objects.get(permalink=pagename)
    context = {
        'title': pg.title,
        'content': pg.bodytext,
        'last_updated': pg.update_date,
        'page_list': Page.objects.all(),
    }  
    return render(request, 'pages/page.html', context)

I don’t expect you to understand this code right now, but as you can see, the layout of the code makes it easy to follow without you necessarily understanding exactly what’s going on.

Indentation and intuitive use of whitespace are not the only stylistic conventions designed to make Python code more readable. Python has a complete style guide called PEP8. I strongly encourage you to read this document, absorb what it has to say any try to follow PEP8’s recommendations in all of your programming.

Interactive Interpreter

Python is a scripted language. This means that, instead of having to compile code before it can be run, the Python interpreter runs the Python code you write directly.

An incredibly useful feature of the Python interpreter is that it can be used interactively, simply by typing python at a command prompt. Try this now, you should get an output something like this:

C:\Users\nigel\OneDrive\Documents\mfdw_project> python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Those three greater-than symbols (>>>) means that Python is in interactive mode and ready for you to input commands. Try these exercises by typing each command at the Python interactive interpreter (Python prompt) and hitting enter:

  1. 1+2
  2. 4*5
  3. 14/5
  4. 14//5
  5. 14%5
  6. x = "Hello"
  7. y = "There"
  8. print(x+y)
  9. print(x,y)
  10. print(x,y, sep="-")
  11. csv = "one,two,three"
  12. lst = csv.split(",")
  13. lst

How did you go? This is the output you should have seen in your terminal window:

>>> 1+2
3
>>> 4*5
20
>>> 14/5
2.8
>>> 14//5
2
>>> 14%5
4
>>> x = "Hello"
>>> y = "There"
>>> print(x+y)
HelloThere
>>> print(x,y)
Hello There
>>> print(x,y, sep="-")
Hello-There
>>> csv = "one,two,three"
>>> lst = csv.split(",")
>>> lst
['one', 'two', 'three']
>>>

So let’s have a quick look at what we did here.

The first three commands should be easy to follow – you are just using Python as a simple calculator to perform addition, multiplication and division. But what about examples 4 and 5?

In example 4 we are performing what is called integer division, so 14//5 is returning the result of 14 divided by 5, without the remainder. And how would you find out the remainder? Use the modulo operator (%) – which is exactly what we are doing in example 5. So 14%5 returns the remainder after dividing 14 by 5.

In examples 6 to 10, things are getting a bit more interesting. In examples 6 and 7, we are simply assigning a string to two new variables. If you have ever used another programming language, you will notice that neither of these variables have to be declared before assigning a value to the variable. Python shortcuts this extra cruft by creating a variable when you assign something to it.

You will also notice in examples 6 and 7, I didn’t have to declare the new variables as strings. This is because Python is dynamically typed, meaning that Python assumes the type of a variable by what you assign to it. In this case, Python assumes that x and y are strings because you assigned strings to them.

Now that we have assigned the strings “Hello” and “There” to variables x and y respectively, we are employing one of Python’s most useful functions – print() – to print some results out to the terminal. In example 8 we are using the + operator to concatenate – or join together – the two strings.

In example 9, we are using the , to separate x and y, which is basically saying “print x and a space and then print y“. The space is the default separator when printing variables. Like most things in Python, this default behavior can be overridden, which is what we are doing in example 10, overriding the space with sep="-" and now the variables print out with a dash (-) instead of a space separating them.

The last two examples demonstrate how Python can tackle more complex problems in a simple and intuitive way. The string csv might be a single line from a comma-delimited spreadsheet that you need to import into Python. The string class in Python has a large number of methods that allow you to manipulate strings built in.

One of those methods is split(). split() allows you to split a string into a Python list using the string you pass to split() as a delimiter. In this case, we are using a comma (,) as the delimiter which splits our string “one,two,three” at the commas, producing a list of three items (['one', 'two', 'three']).

Testing Code With the Interactive Interpreter

The examples so far have been pretty simple, but the takeaway is that anything that runs in Python will run from the interactive interpreter. This is supremely useful for working out how to write code to solve a problem or produce the output you want.

This simple, iterative way that you can work with Python makes the development process much quicker and far less painful that the “write-compile-test-rewrite” cycle of other programming languages.

You can test code with the interactive interpreter by simply cutting and pasting the code from your editor into the terminal window, or you can type the code in at the interpreter command prompt. It’s important to understand, however, how Python interprets more complex code. For example, type this into the interactive interpreter:

for i in range(5):

This is the start of a for loop (more on for loops a bit later). For the sake of this example, I am using the for loop to demonstrate what Python does with this command. Notice, that Python dropped to the next line and instead of the command prompt (>>>), there is now an elipsis (...). This is because Python is waiting for more input from you.

This is where most beginners trip up, remember – whitespace matters. So if you just start typing at the elipsis this is what happens:

>>> for i in range(5):
... print(i)
File "<stdin>", line 2
    print(i)
        ^
IndentationError: expected an indented block
>>>

The interactive interpreter doesn’t automatically indent your code – you have to add the indentation yourself. You can do this by either adding four spaces, or hitting the tab key, like so:

>>> for i in range(5):
...     print(i)

You will need to hit enter once more to tell Python that you have finished entering code and the loop will run:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
>>>

Very cool. To exit the interactive interpreter, you can either type exit() at the Python prompt or type CTRL-Z on your keyboard and hit enter, which will take you back to your standard system command prompt:

>>> exit()
C:\Users\nigel\OneDrive\Documents\mfdw_project>

Using the Interactive Interpreter with Django

Using the standard Python interactive interpreter is great for testing general Python code, but what if you want to test code from your Django project? If you try and run any Django code from the Python prompt, the first error you are likely to encounter is “No module named 'django'.”

This is because Python has no knowledge of Django when you install it in a virtual environment and because your Django project requires a few files loaded (particularly settings.py) to be able to run. Fortunately, Django’s developers thought of this and provided a convenient management function that allows you to use the Python prompt with Django.

First, start up your virtual environment like so:

C:\Users\...\mfdw_project> env_mfdw\scripts\activate

Then change into your mfdw_site directory and run the command python manage.py shell:

(env_mfdw) C:\Users\...\mfdw_project> cd mfdw_site
(env_mfdw) C:\Users\...\mfdw_project\mfdw_site> python manage.py shell
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

This looks just the same as a Python prompt, but now you can access everything within your Django project, for example, your Project settings:

>>> from django.conf import settings
>>> settings.DEBUG
True
>>> settings.BASE_DIR
'C:\\Users\\nigel\\OneDrive\\Documents\\mfdw_project\\mfdw_site'
>>> settings.LANGUAGE_CODE
'en-us'
>>>

If you want to see all the settings, type in:

dir(settings)  # Be warned, it's a long list! 

There’s not a lot more we can play with right now as your project is only an empty shell, but we will be revisiting the Django/Python interactive interpreter a few times in the book, so you will have plenty of chances to test it out.


Want my new Django book for beginners for half price?

I have a new book for beginners coming out very soon (by end of June if all goes to plan!).

In this new book I answer the big questions I get from beginners:

  • Why should I use Django?
  • What problems does Django help me solve?
  • What if I don’t know Python?
  • Please, can you give me something real? Something I can build and show off to my friends, or a potential employer – not just snippets like everyone else on the Internet?

Written for Django 1.11 and Python 3.6, the book teaches you to program using the absolute latest version of Django and Python.

By the end of the book you will not only know all of the basics to writing an awesome Django website, but you will have a functioning website ready for deployment, or to demonstrate to an employer – Or to show off to your friends 🙂

Anyone who signs up below will not only get to be a part of an exciting book launch, but will get the eBook version for half price as a part of a limited time launch special!

Will send you more information by email closer to launch day.