Passing parameters to Django admin action

By : Akshar Raaj

This post will show how to pass parameters to custom Django admin actions.

This post assumes that you have an idea of Django actions.

Django provides a default admin action which is 'Delete selected rows'. Changelist page for all the models registered with admin has this action available. This action allows to select multiple rows and delete them in a single POST request.

Problem statement

We want to allow following Django action from admin.

  • There is a model called Instrument. It has a field price
  • Allow selecting multiple rows for this model and update the value of price for selected ...

more info..
Topics : django

Method decorators in Python

By : Akshar Raaj

This post assumes you have a basic understanding of Decorators. If not, you can read our introductory post on Decorator

Method decorators

In introductory post, we learnt about function decorators. In this post we'll see method decorators:

Let's write a Class and a method on it which we will decorate later.

>>> class Person(object):
...     def __init__(self, name):
...         self.name = name
...     def print_name(self):
...         print self.name

Create a Person instance. p1 refers to the created instance.

>>> p1 = Person("eddard")

Call print_name on Person.

>>> p1.print_name()
eddard     #output

Something worth noting about previous Python statement. Quoting from docs ...

more info..
Topics : python Decorators

Minimal Gunicorn configuration

By : Akshar Raaj

Gunicorn is an http server written in Python. It is a WSGI compliant server and can serve web applications which are compliant with WSGI. This would help if you aren't comfortable with WSGI.

We will serve a basic web application using Gunicorn. And see the minimal and must configuration settings you should set while using gunicorn. We will specify the configuration variables in an external file and will direct gunicorn to use that configuration file.

Web application

We are working in directory /tmp and have activated a virtual environment called PythonEnv

(PythonEnv)/tmp $

Let's write the web application ...

more info..
Topics : python gunicorn

Supervisor with Django and Gunicorn

By : Akshar Raaj

Supervisor with Django: A starter guide

This post assumes that you have used gunicorn and know what it does. I will try everything inside a virtual environment and hope you do the same.

What is supervisor.

Supervisor is a monitoring tool that can monitor your processes. It can restart the process if the process dies or gets killed for some reason.

Use of supervisor: Why I started using it.

In production, I use gunicorn as web server. I started a gunicorn process as a daemon and logged out from the server. My site ran as expected for few days. All ...

more info..
Topics : django supervisor

Django backward relationship lookup

By : Akshar Raaj

I often limit the lookup to fields of the model and forget about backward relations.

Consider the following relationship:

class Group(models.Model):
    name = models.CharField(max_length=100)

class Student(models.Model):
    name = models.CharField(max_length=100)
    group = models.ForeignKey(Group)

A group can have many students.

We want to get the groups based on certain conditions on model Student. An example is getting the groups which contain a student named 'stud1'. If you can get it using model Group and without using Student, you can skip this post.

In such a scenario, we tend to use Student model. It ...

more info..
Topics : django

Producer-consumer problem in Python

By : Akshar Raaj

We will solve Producer Consumer problem in Python using Python threads. This problem is nowhere as hard as they make it sound in colleges.

This blog will make more sense if you have some idea about Producer Consumer problem.

Why care about Producer Consumer problem:

  • Will help you understand more about concurrency and different concepts of concurrency.
  • The concept of Producer Consumer problem is used to some extent in implementing a message queue. And you will surely need message queue at some point of time.

While we use threads, you will learn about the following thread topics:

  • Condition in threads ...

more info..

State pattern with UI Code

By : Akshar Raaj

This blog tells how I used state pattern in my UI code, and explains state pattern with JavaScript and jQuery.

Disclaimer:

  • This blog will not talk much about benefits of State pattern as there is already a lot written about it. It only gives a practical example of using state pattern with UI code.
  • I am not much confident about difference between State pattern and Strategy pattern. Let's discuss if I misunderstood State pattern.

Use case:

  • I have a page with two input fields.
  • Page initially has one title field and one body field.
  • There is a '+Add' button ...

more info..

Understanding Threads in Python

By : Akshar Raaj

We will see some examples of using threads in Python and how to avoid race conditions:

You should run each example several times to notice that threads are unpredictable and that your results differ every time.

Disclaimer: Forget anything you heard about GIL for now, because GIL is not going to mess up with scenarios I want to show.

Example 1:

We want to fetch five different urls:

Single threaded way:

def get_responses():
    urls = ['http://www.google.com', 'http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com']
    start = time.time()
    for url in ...

more info..
Topics : python threads

Process and Threads for Beginners

By : Akshar Raaj

We will cover this post in following sequence:

  • Process and multiprocessing
  • Threads and multithreading

Process and multiprocessing

A process is an executable instance of a program.

Example:

You write a java program and save it as abcd.java and run it with java abcd. While this program is executing it is a process. File abcd.java is not a process, but when it's executing it is a process.

You write a Python program and save it as abcd.py and run it with python abcd.py. So, while this program is executing it is a process. Once the program ...

more info..
Topics : threads process

Minimal Nginx and Gunicorn configuration for Django projects

By : Akshar Raaj

We will see how to deploy a Django project with nginx and gunicorn.

It was easier for me to understand nginx and gunicorn on development machine and then move to a publicly accessible server. So, we will cover this post in a similar sequence:

On development machine

  • Use django's runserver to serve the site.
  • Stop runserver and start using gunicorn instead.
  • Add nginx to this configuration.

On server

  • Deploy the project on a publicly accessible server using same stack.


Use runserver

We will use a minimal project with two apps and few static files. You can view this project ...

more info..

Basics of WSGI

By : Akshar Raaj

In this post we will write a web app which will serve few urls. We will not use any Python framework for it. It's only to illustrate how things work under the hood.

Before we start, let's clarify few terms we will be using.

  • Web Server: When we say web server, we mean the software, and not the machine that stores your code. This server recieves the request from a client(Web browser) and returns a response. Web server doesn't create the response, it only returns the response. So, a server needs to talk with a Web ...

more info..
Topics : python WSGI

Common testing scenarios for Django app.

By : Akshar Raaj

People are often confused regarding what tests to write. Let's look into some scenarios for which tests can be written.

Setting up the project

We start a Django project inside a virtual environment. In this post we would be using django 1.4.

(dj)~/play/dj$ django-admin.py startproject testcases

Let's start an app named blog.

(dj)~/play/dj/testcases$ python manage.py startapp blog

We will have the following model in blog/models.py:

class BlogEntry(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()
    is_published = models.BooleanField(default=True)
    user = models.ForeignKey(User)

We ...

more info..
Topics : django testing

Serving static files in Django

By : Akshar Raaj

Serving static files, especially during development, is frequently a pain point. In this post, we will discuss the various settings and directory structure and how they interact with each other. Let's start with development when you have DEBUG = True.

We will create a Django project from scratch so that we are fully aware about what file in what directory we are talking about. So, this blog post will be a little longer than it should be. We will try these things with Django 1.4, but these will work on Django 1.3 as well. I have not tested ...

more info..
Topics : django static

Understanding decorators

By : Akshar Raaj

Understanding decorators in Python

We will divide this post into two topics

  1. Functions are objects and they can be passed around.
  2. Writing few decorators

As usual, I will be trying out the code in ipython and I suggest you to do the same.

Functions can be passed around similar to any other object in Python.

If you are already familiar with this, you can skip to next section.

Let's first write a class.

>>> class A(object):
...     def __init__(self, a):
...         self.a = a
...

Let's create an instance of this class.

>>> obj = A(5)    
>>> print obj.a
5                 #output ...

more info..

Metaclass in Python

By : Akshar Raaj

In this post we will be talking about Metaclass in python. If you are reading some code which uses metaclass, you will probably come across __new__. If you are not familiar with what __new__ does, i suggest you first read about __new__.

You can read about __new__ in our last to last post

Throughout this post we will be talking about new style classes. Things might differ in old-style classes.

As we go, i will be trying everything on IPython and suggest you as well to try everything on IPython.

Let's see a little bit about normal Objects in ...

more info..

__new__() in python

By : Akshar Raaj

Lately I started looking into Django code and wish to write about internals of Django. I started with Django models and will be writing about it soon. For understanding how Django models work, I had to understand what metaclasses are and how metaclasses work. Metaclasses use method "__new__" and so I looked at what "__new__" does.

As __new__ is a static method, we will see a lttle bit about static methods and then __new__ in detail.

  1. Understanding static methods.

  2. Understanding method "__new__" of any class. We will see how to override method __new__ in a class.

Also, I will be ...

more info..

Understanding '*', '*args', '**' and '**kwargs'

By : Akshar Raaj

When i started learning Python, i was very confused regarding what args, kwargs, * and ** does. And i feel there are few like me who had this confusion and problem. With this post, i intend to reduce (hopefully i can eliminate) that confusion.

Throughout this post, i will be using ipython and i suggest you to try everything on ipython as well. We will intentionally make some mistakes along the way, so that we can understand this topic better.

Let's divide our work under five sections:

  1. Understanding what '*' does from inside a function call.
  2. Understanding what '*args' mean inside a ...

more info..
Topics : python args kwargs

Getting started with South for Django DB migrations

By : Akshar Raaj

South is a migration tool used with Django.There will be times when you would be adding fields to a model or changing the type of field (eg: Field was an IntegerField and you want to change it to FloatField). In such cases syncdb doesn't help and South comes to your rescue.

There were times when i tried "python manage.py migrate southapp", got some error and then tried "python manage.py migrate southapp 0001 --fake". In some cases, that worked. When it did not work, i tried something else and so on. There were confusions regarding what --fake ...

more info..
Topics : django South south

How to use jsTree

By : Akshar Raaj

Using jsTree

Problem Statement:

To show a TreeView (hierarchical view of information) structure in a Web page.

I came across this problem when i was required to develop a web application which allows its users to store contacts and their related information(name, email, phone). The contacts would go into a folder and any folder can have any number of subfolders and any subfolder can have any number of contacts. Also, the folder structure can be nested as many levels deep as the user wants. So, how do you show the folder structure in a Web Page?

You might encounter ...

more info..

Setting up your system to start with Django development on Ubuntu:

By : Akshar Raaj

1>Being a Python web framework, Django requires Python. If you are on ubuntu, you probably have python installed on your system. If you don't have it installed, give the following command from the terminal:

sudo apt-get install python

This will install Python on your machine.

2>If you will be developing a database driven web application, you need to have a database setup on your system. I feel mysql is good and will tell you about installing mysql. It is pretty easy to install and use. You need to issue the following command from terminal:

sudo apt-get install ...

more info..
Topics : django setup mysql
© Agiliq, 2009-2012