GIT – Merge dev to master

I generally like to merge master into the development first so that if there are any conflicts, I can resolve in the development branch itself and my master remains clean.

(on branch development)$ git merge master
(resolve any merge conflicts if there are any)
git checkout master
git merge development (there won't be any conflicts now)
git push

DateTime functions in Python

Some useful date/time functions in Python:

import time
import datetime
from time import gmtime, strftime
from datetime import timedelta, date
from dateutil.relativedelta import relativedelta

def validateApiDate(apiDate):
    Validates non-standard date string format
        dt = datetime.datetime.strptime(apiDate, '%Y%m%d').date()
        #print type(dt)
        dt = datetime.datetime.strftime(dt, '%Y-%m-%d')
        print dt
    except ValueError:
        return False

def addDaysToCurrentDate(numDays):
    Add days to current date
    d = + timedelta(days=numDays)
    return int(time.mktime(datetime.datetime.strptime(str(d), '%Y-%m-%d').timetuple()))

def getTimeDelta(numDays):
    Add days to current date
    d = + timedelta(days=numDays)
    return d.timetuple()

def validatePastDate(d):
    Validate if the date is a past date
    dt = datetime.datetime.strptime(d, '%Y%m%d').date()
    #print type(dt)
    today =
    #print type(today)
    diff = (dt-today).days
    #print type(diff)
    print diff

def first_of_last_month():
    Get 1st of last month. Works with python 2.7 and higher
    one_month_ago = + relativedelta(months=-1)
    first_day_last_month = (one_month_ago.year, one_month_ago.month, 1)
    return first_day_last_month

def first_of_last_month_py26():
    Get 1st of last month. Works with python 2.6 or older
    first_day_of_current_month =
    last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)
    first_date_of_last_month = last_day_of_previous_month.replace(day=1)
    return first_date_of_last_month

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'),