Python Django Tutorial 5 – The built in Admin interface

1. Installing the Admin
Open the settings file and make sure that the following item is added to the INSTALLED_APPS set.


2. Enable Admin URL’s in the project’s file
After importing the admin module, enable/add the following pattern in the list of urlpatterns:

from django.contrib import admin
urlpatterns = [
    url(r'^admin/', include(,

3. Register the App’s models that need to be shown in Admin
Open the file created under the articles directory and register the models in this file.

from django.contrib import admin
from article.models import Article

# Register your models here.

Now you should be able to add/edit/delete your articles from the admin panel. How cool is that!

Python – Ternary operator

Programming languages derived from C usually have following syntax:

(condition) ? (expression1) : (expression2)

The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic, since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its own shortcut conditional expression:

(expression1) if (condition) else (expression2)
e.g. reuse_appliances = True if use_existing_systems == 'True' else False

Python Django Tutorial 4(b) – Advanced views and urls

1. Defining URL’s within the App
So far, we had defined all URL’s in the main project’s file. But the purpose of having an app is that it can be a standalone module that can be plugged into any other project. For the same reason, it is nice to define all the URL’s related to the app contained with the app.

Create a new within the articles app. This is explained as per Django version 1.8. URL imports works in a different fashion for older Django versions.

from django.conf.urls import patterns, include, url
from article.views import articles, article

urlpatterns = [
	url(r'^all/$', articles, name='articles'),
	url(r'^get/(?P<article_id>\d+)/$', article, name='article'),

The part of code (?P<article_id>\d+) denotes a variable/parameter (?P) is named article_id will be of type digit of any length greater than 1 (\d+).

Now modify the within the project folder so that it is able to include the file that is created under the articles app.

urlpatterns = [
    url(r'^articles/', include('article.urls')),

The above denotes that anything starting with articles will look for the next segment of the URL within the article.urls file.

2. Creating views
Let’s define 2 more views in the file under articles. The first one would take the article_id parameter from the URL and use it to show the article header and body, e.g. view for this URL

def article(request, article_id = 1):
	return render_to_response('article.html', {'article' : Article.objects.get(id=article_id)})

This view takes in a new parameter article_id apart form the standard request parameter. If you look back, the name of the parameter is defined within the URL (?P

\d+). The view calls the magical render_to_response by passing in the article object corresponding to the article_id.

The other view would list all the articles in the database, e.g. view for this url

def articles(request):
	return render_to_response('articles.html', {'articles' : Article.objects.all()})

This view passes all article objects to the template articles.html

3. Creating templates
The first template (article.html) takes in a single article object and displays it’s title and body.

<h1>{{ article.title }}</h1>
<p>{{ article.body }}</p>

The second template (articles.html) lists all the articles in the database with a link to access their individual article page.

{% for article in articles %}
<h2><a href="/articles/get/{{ }}/">{{ article.title }}</a></h2>
<p>{{ article.body }}</p>
{% endfor %}

Python Django Tutorial 3 – views, simple urls and basic templates

A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.

Create a simple view hello that will take the request from url HOSTNAME/hello and return a simple HTML page with a custom welcome message. Create the following view function in the file created by default in the Article app. You will have to import HttpResponse from django.http module in order to return the HtmlResponse from the view.

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def static_hello(request):
	name = 'Varun'
	html = "<html><body><h4>Hi %s,<br />This seems to have worked!</h4></body></html>" % name
	return HttpResponse(html)

2. URL
Now, we need to create a mapping so that Django can relate to the URL entered in the browser and pass on the processing to the hello view that we defined. We do this in the file created by default in the django_test project directory.

from article.views import hello
urlpatterns = [
    url(r'^admin/', include(,		#-- Added by default by Django
    url(r'^static-hello/', static_hello, name='static_hello')

Now navigate to and you’ll notice that the HTML response is showed on the page.

3. Template
A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. Create a new directory called templates in the project home (where you have After creating this directory, modify the settings file so it can look for templates in this directory.

'DIRS': ['/Users/varun.verma/Work/scripts/python/setup/django-default/django_test/templates'],

The path for templates directory should be absolute and not relative.

Now let’s try to modify the view to render a response via a template. We’ll need a few imports to start with:

from django.template.loader import get_template

get_template is a helper function that helps get the template information from the settings file.

from django.template import Context

Context is important for Django template to understand how to render.

Create a new view in the file:

def dynamic_hello(request):
	name = 'Varun'
	template = get_template('dynamic_hello.html')    # Load the template
	html = template.render(Context({'name' : name})) # Render the template with our local Context
	return HttpResponse(html)                        # Send HTTP Response back

Create a new file dynamic_hello.html in the templates directory:


Hi {{ name }}, <br/>
This Dynamic Template seems to have worked.

Add a new URL to the file that can invoke the new dynamic_hello view:

from article.views import static_hello, dynamic_hello
urlpatterns = [
    url(r'^admin/', include(,
    url(r'^static-hello/', static_hello, name='static_hello'),
    url(r'^dynamic-hello/', dynamic_hello, name='dynamic_hello'),

Now navigate to and you’ll notice that the dynamic HTML response is showed on the page.

4. TemplateView / Class based views
Class-based views provide an alternative way to implement views as Python objects instead of functions. Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.

from django.views.generic.base import TemplateView
class HelloTemplate(TemplateView):
	template_name = 'hello_class.html'

	def get_context_data(self, **kwargs):
		context = super(HelloTemplate, self).get_context_data(**kwargs)
		context['name'] = 'Varun'
		return context

Create a new file hello_class.html under the templates directory defined in the settings file


Hi {{ name }}, <br/>
This Class Based view Template seems to have worked.

Add new URL,

from article.views import HelloTemplate
url(r'^classview-hello/', HelloTemplate.as_view(), name='classview_hello'),

5. render_to_response
Last but not the least – render_to_response. We saw earlier a 3 step approach to taking a request and returning a Http Response – load a template, render the template with the Context and return Http Response. render_to_response can do all of that by itself.

from django.shortcuts import render_to_response
def simple_dynamic_hello(request):
	name = 'Varun'
	return render_to_response('dynamic_hello.html', {'name' : name})

Add new URL:

from article.views import simple_dynamic_hello
url(r'^simpledynamic-hello/', simple_dynamic_hello, name='dynamic_hello'),

Python Django Tutorial 2 – and database models

1. Setup

By default, it’s automatically setup to use SqlLite with the default db being db.sqlite3 file created in your django_test application directory created in Tutorial 1.

Set Language Code and Time Zone

TIME_ZONE = 'America/Los_Angeles'

2. Create a new App inside the project
Navigate to the django_test directory and create a new app called article.

python startapp article

An empty file called is created in the article directory. This tells python that article is a package that can be imported as a module. The other files that are created are, and For now we will concentrate only on

3. Create models
Create a simple model for the article app in

from django.db import models

# Create your models here.
class Article(models.Model):
	title = models.CharField(max_length=200)
	body = models.TextField()
	pub_date = models.DateTimeField('date published')
	likes = models.IntegerField()

4. Syncdb
Execute syncdb to build django tables and to setup the superuser.

python syncdb

Deprecated since version 1.7:
This command has been deprecated in favor of the migrate command, which performs both the old behavior as well as executing migrations. It is now just an alias to that command.

5. Add application to INSTALLED_APPS
You’ll soon realize that syncdb did not create the tables for the class defined in This is because the app isn’t listed under INSTALLED_APPS yet. In order to do that, open the file and add the following line to it:


6. Run migrations
After running syncdb, you’ll get a warning to use migrations. Use the following command to create and apply migrations

$ python makemigrations
Migrations for 'article':
    - Create model Article

$ python migrate
Running migrations:
  Rendering model states... DONE
  Applying article.0001_initial... OK

If you ever wanted to drop the application tables entirely from DB, run the following command:
python reset article

7. Using shell
To access the data, you can use the shell command to view, add or alter data.

8. Use the __unicode__ method to make the object data more meaningful

from django.db import models

# Create your models here.
class Article(models.Model):
	title = models.CharField(max_length=200)
	body = models.TextField()
	pub_date = models.DateTimeField('date published')
	likes = models.IntegerField()

	def __unicode__(self):
		return self.title

Python Django Tutorial 1 – Installing easy_install, virtualenv & django

1. Install easy_install via python-setuptools
easy_install – used to get python modules from PyPI (Python Package Index). easy_install script is part of the package called python-setuptools. The recommended way to bootstrap setuptools on any system is to download and run it

sudo python

using the target Python environment. The other way to install on some linux systems is to use sudo apt-get install python-setuptools

2. Use easy_install to download virtualenv
virtualenv is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need. This keeps your global site-packages directory clean and manageable.

sudo easy_install virtualenv

Those are the 2 main applications that we need to install the sudo command. Once we’re done with those, we can start using virtualenv to cordon off our modules into a separate folder that won’t accept our main system. So we won’t have to use sudo anymore.

3. Create a new virtualenv directory for the django installation
Create a new directory for your virtualenv by running:

virtualenv --no-site-packages django-default

The –no-site-packages isolates your environment from the main site packages directory. You should get an output similar to:
New python executable in django-default/bin/python
Installing setuptools, pip, wheel…done.

4. Activate the new virtual environment
Now we need to activate the newly setup virtualenv so that any new installations from now one are put in our virtual environment and not in our root folder. In order to do that, run the following command:

source django-default/bin/activate

Now the shell will change the context into the current environment. Now any easy_install, pip will work in the current environment.

5. Install django in the virtualenv
Use easy_install to install django in the virtualenv.

easy_install Django

You will no longer require root/sudo permissions to do that because you’re now using this setup in your local environment. This will install the django-admin application in the bin directory.

6. Create a django project in the virtualenv
Use django-admin application to create the first django application: startproject django_test

This will create a directory django_test with the project files. We have a file along with the project folder. The file is important to develop your application in terms of configuring your system, setting of your web server, etc

7. Run server using
Run your server by running the following command in your django project directory (django_test):

python runserver

You should get a similar output to ensure that your server is up and running:
Django version 1.8.2, using settings ‘django_test.settings’
Starting development server at
Quit the server with CONTROL-C.

Navigate to from your browser and you should see a congratulations message signalling that your django site is up and running.

8. Deactivate/Exit the virtualenv
Just execute


from the virtualenv shell to exit the virtualenv you’re working on and return to the main shell.