Deploying Django apps on Heroku

By : shabda

Deploying Django apps on Heroku:

Read this first: http://devcenter.heroku.com/articles/django.

This is a great article by the Heroku. I am just filling in some more details and making this step-by-step.

  1. Get your Django project code.
  2. Create a virtualenv with a no-site-packages command ::

    virtualenv vent --no-site-packages

  3. Install Django, psycopg2 (postgres connector), gunicorn and any other required Django libraries.

  4. Confirm that you have all the required libraries and you can run your code locally using manage.py runserver.
  5. Create a requirement.txt by using ::

    pip freeze > requirements.txt
    
  6. Make sure you have a requirements.txt at the root ...

more info..
Topics : django

Deploying Django apps on Heroku

By : shabda

Read this first: http://devcenter.heroku.com/articles/django.

This is a great article by the Heroku. I am just filling in some more details and making this step-by-step.

  1. Get your Django project code.

  2. Create a virtualenv with a no-site-packages command

    virtualenv vent --no-site-packages
    
  3. Install Django, psycopg2 (postgres connector), gunicorn and any other required Django libraries.

  4. Confirm that you have all the required libraries and you can run your code locally using manage.py runserver.

  5. Create a requirement.txt by using
    pip freeze > requirements.txt
    
  6. Make sure you have a requirements.txt at the root of your repo. Heroku uses ...

more info..
Topics : django

How to use pep8.py to write better Django code

By : shabda

Here is another or screencast I created for my "Getting Started with Django" series. Like this? Email us on what would you like to see.

(Watch in fullscreen.)

more info..
Topics : django screencasts

Screencast: Django Tutorial Part 1

By : shabda

Django Screencast Tutorial 1 from Shabda Raaj on Vimeo.

I am creating screencasts for Django tutorial and other Django videos. Here is part 1. Liked this? Leave me a comment or email me and tell me what would you like me to create screencasts for.

(Watch the screencast in full screen mode.)

more info..
Topics : django

How and why to use pyflakes to write better Python

By : shabda

Here is another of the screencasts I created for "Getting started with Python" series. Liked them? Let me know what else would you like me to create screencasts about?

more info..
Topics : django screencasts

Writing jQuery plugins using Coffeescript

By : shabda

So you want to write a Jquery plugin. If you know jQuery and Coffeescript, this would be amazingly easy.

I will walk you through writing a jQuery plugin which will allow us to add alternating colors to alternating rows.

Here is the plugin in its entirety.

$ = jQuery
$.fn.zebraTable = (options) ->
    defaults = 
        evenColor: '#ccc'
        oddColor : '#eee'

    options = $.extend(defaults, options)
    @each ->
        $("tr:even", this).css('background-color', options.evenColor)
        $("tr:odd" , this).css('background-color', options.oddColor)

Lets look at what we did.

  1. We bound $ to jQuery object.
  2. We created an anonymous functions and added this to jQuery, by assigning it to $.fn ...

more info..
Topics : coffeescript

Haml for Django developers

By : shabda

Haml is taking the Ruby(and Rails) world by storm. Its not used as heavily by Python(and Django) developers as the Python solutions aren't as mature. I finally gave Haml a try and was pleasantly surprised how easy it was.

The most mature Python implementation of Haml is hamlpy, which converts the hamlpy code to Django templates. Others are shpaml and GHRML

Lets look at some templates from Django tutorial

{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% endif %}

Here is this template converted to Haml

-if ...

more info..
Topics : django

Coffeescript for Python programmers

By : shabda

I just learnt Coffeescript, and as a Python programmer loved being able to write Javascript in a Python like language. Coffeescript is inspired by Python/Ruby and is very close to these languages. Writing Coffeescript and reading the compiled Javascript also improved my understanding of Javascript. Without much ado here is translation of some Python code to Coffeescript to get you started.

Defining a variable

Python
a = 10

Coffeescript
a = 10

Setting scope is done via whitespaces.

Python

if i == 10:
    foo()

Coffeescript

if i == 10
    foo()

No semicolons

List comprehensions

Python

languages = ["Python", "Coffeescript", "Java", "Ruby", "Haskell"]
languages = [lan ...

more info..
Topics : coffeescript
shabda
Comments
Reactions

Jobs

By : shabda

We are a small software company building web facing applications for a number of clients. We work with Python, Django, Jquery, Mysql or Postgres. We “build amazing webapps”. You can learn more about us from:

What we are looking in you:

  • Are you a software engineer looking to work in a small team with smart people?
  • Do you know multiple programming languages, and have the ability to pick up new ones?
  • Can you prove why your IDE or editor is better than mine?
  • Do you know relational databases, when ...

more info..
Topics : jobs
shabda
Comments
Reactions

Comparison of mobile app frameworks: Iphone, Java, Phonegap and Titanium

By : shabda

I recently built the same app with the common mobile technologies, Obj-C, Android:Java, Phonegap, and Titanium .

This is a quick comparison of the app frameworks.

Miscellaneous notes

  1. Phonegap and Titanium both amazed me. It feels very empowering to code in Html, css and JS, test it in Chrome, debug it with firebug, and deploy to a device without any changes. Titanium UI widgets are native, building it with JS was very cool.
  2. Phonegap and Titanium both underwhelmed me. I assumed Phonegap would have widgets which would be 95% of the way to looking like native widgets. It was easy ...

more info..
Topics : iphone android mobile
shabda
Comments
Reactions

Getting started with Titanium development for Android and Iphone

By : shabda

This is the third post in our mobile app development series. ( You may want to read Phonegap and Android with Java.)

Like last time we will build an App which allows calculating the tax payable, per the rules here. We will use Titanium Mobile

Installing Titanium

Download and install the fairly small Titanium from their sites. Once you download and start it, it will download and install more components. You can then create a new project from their UI.

Layout the Layout

You can add UI widgets and lay them out using Javascript. You need to use Titanium's API ...

more info..
shabda
Comments
Reactions

Getting started with PhoneGap using Xcode for Mobile app development

By : shabda

This is next in the series of apps I am building using various mobile technologies. It is the same app as build using Java for Android for calculating the Tax payable (in India). You can get the code for Objective-C, Java-Android, and PhoneGap.

First the impressions

Phonegap was the easiest to work with among the Objective-C, Java and PhoneGap, by far. I created the app as easily as

Step 1. Write the app and test it in Browser using the Chrome developer tools. Step 2. Start a project in Xcode. Step 3. Copy the HTML and CSS files to project ...

more info..
Topics : iphone android mobile
shabda
Comments
Reactions

Starting Android app developement: From zero to app

By : shabda

We recently started with Mobile Application development. I am learning Android using the Commonsware book, and highly recommend it. This is a very short guide to getting you running your first Android app.

What will we build

We will build a simple tax calculator for India, per the rules given here for tax calculation. In this app, we need to gets users income and various tax deductible expenses. After that we need to update the UI to show the tax. You can see the final app and code on github here.

Setting up

  1. Install Java and Eclipse
  2. Install Android SDK ...

more info..
shabda
Comments
Reactions

Book Review: Pragmatic Guide to JavaScript

By : shabda

Pragmatic Guide to JavaScript is the Pragprog's book by Christophe Porteneuve which I have wanted to read for a while.

I went into this book expecting to read actionable and task focussed book on modern JavaScript, and this book does not disappoint on that count. Using 35 tasks which you are going to need in your browser based JS development, this books teaches required JS techniques.

However I went into the book expecting a framework agnostic approach. This book however is very heavily focussed on Pototype. Initial chapters start as framework agnostic, but they soon turn into Prototype based ...

more info..
Topics : book reviews

Book review: The Principles of Successful Freelancing

By : shabda

The Principles of Successful Freelancing is book I read after The Principles of Project Management.

My motivation from this book was to use freelancing advice and use that for our (larger) business. This book is razor focussed on Freelancing and even more on people who are starting with or considering starting freelancing. If you are in this group I consider this book very well written, and a must read, but if you are part of a larger group, the razor sharp focus makes this not worthwhile.

Chapter wise it is:

  1. Chapter 1: Considering Freelancing?
  2. Chapter 2: Prepare for the Transition ...

more info..
Topics : book reviews
shabda
Comments
Reactions

Book review: The Principles of Project Management

By : shabda

The Principles of Project Management is the book I am reading after Outsourcing Web Projects.

I went into this book expecting lot of actionable steps I can use for our projects right away, however this book is heavier on theory. Guess I can not complain with the name being The Principles of Project Management.

In their own words the book has,

So What Is Project Management Anyway?

This chapter forms an introduction to the art and science of project management. Here, we talk about the key phases every project goes through and why project management skills are increasingly important today ...

more info..
Topics : book reviews
shabda
Comments
Reactions

Book Review: Outsourcing Web Projects.

By : shabda

Sitepoint had a book sales running recently where they made all their books available for sale at 7$. Being a sucker for good books and deals, I bought more than I should have. Here is the review of the first I read, "Outsourcing web projects."

This books is written from the viewpoint of buyers, but as a vendor, I have some insights (IMO) from the other side.

It starts with these chapters.

  • How to Have Vendors Competing for your Job.
  • How to Find the Perfect Outsourcing Partner.
  • How to Get the Best Price for your Project.
  • How to Get it ...

more info..
Topics : book reviews

The Unfuddle Tutorial

By : shabda

Unfuddle is the tool we use for our non open source development. I have found it to be the best tool for Software Project management, in particular I think it is superior to Basecamp and Assembla.

When you start using Unfuddle, the number of things can seem overwhelming. This tutorial should help you Unfuddle the Unfuddle.


The Unfuddle Glossary

Unfuddle has,

  • Projects: Top level Things which need to be done.
  • User: People who are working on a given project.
  • Ticket: What a User works on.
  • Milestone: A timed list of tickets which should be completed before this given time ...

more info..
Topics : tips tutorial
shabda
Comments
Reactions

Experiments in URL design.

By : shabda

Keeping url structure sane plays a major role in user experience, by making it easy to go to specific pages and navigate the site. Some real world urls and how they could have been better follow.


The Bad Urls:

  • http://news.ycombinator.com/item?id=1967820
  • http://area51.phpbb.com/phpBB/viewforum.php?f=99
  • http://msdn.microsoft.com/en-us/aa336522.aspx

The Good

  • Easy to develop for. The id referred is the Primary key

The Bad

  • Hard for users to select the correct page from a url bar dropdown
  • Bad for SEO

Neutral:

  • Easy to guess next and previous ...

more info..
Topics : opinion web2.0 apps urls
shabda
Comments
Reactions

Unfuddle Summary Script

By : shabda

Unfuddle is our preferred tool for private repos, project management and ticketing. We recently wrote a slick script to summarize our Unfuddle status. So here is it.


import getpass
import simplejson
import sys
import urllib2

from datetime import datetime, date

try:
    from settings import *
except ImportError:
    ACCOUNT_DETAILS = {
        'account': '',
        'username': '', 
        'password': '',
    }
    SEND_MAIL = False

if not ACCOUNT_DETAILS['account']:
    ACCOUNT_DETAILS['account'] = raw_input('Enter unfuddle account name: ')

if not ACCOUNT_DETAILS['username']:
    ACCOUNT_DETAILS['username'] = raw_input('Username: ')

if not ACCOUNT_DETAILS['password']:
    ACCOUNT_DETAILS['password'] = getpass.getpass()

class Unfuddle(object):
    def __init__(self):
        self.base_url = 'https://%s.unfuddle.com' % (ACCOUNT_DETAILS['account'])
        self.api_base_path = '/api/v1/'

def get_data(self ...

more info..

Github in github

By : shabda

We have a (semi) new app. This takes your Github account and creates Github pages from it. It displays a summary of your account, and of all your apps. Get it at github


Readme

Takes a github account, creates html pages for it, and puts it on Github pages.

How it proceeds.

  1. Get data for specified account from Github API
  2. Uses Jinja2 to write ReST docs.
  3. Build html from the ReST docs.
  4. Pushes the html to a Git repo from which you build github pages.

tl;dr: Yo dawg, I heard you like github, so I put a github in ...

more info..
shabda
Comments
Reactions

I am so starving: Web app in python frameworks.

By : shabda

I have written the same web app in various web frameworks. Get it from Github.

Copied from the Readme.

This is a set of apps which creates the same application in various Python web micro-frameworks.

The app(s) talks to Facebook, and finds out recent people who have posted a public status with the text "so starving".

This idea came from reading Onion.

We have the same app in these frameworks.

Microframeworks:

Full stack frameworks:


If the framework included template engine and caching, that was used directly. Otherwise ...

more info..
Topics : python

Importing wordpress

By : shabda

We now have a way to import wordpress to blogango, and all our old posts are on this blog.

Thanks for reading.

more info..
Topics : django wordpress
shabda
Comments
Reactions

Getting trending Github projects via YQL

By : shabda

Github.com/explore allows you to see the trending Github topics. They use repopular.com for this, which use twitter retweets to find out the popular Github repos.

Since neither Repopular, nor Github have a RSS of these trending repos, I wanted to get a list of these. Here is how easy it is with YQL.

How we do it

  • Go to YQL console. Give the SQL query to get the data from the webpage.

  • where url="repopular.com" and css="div.pad a" is the magic which select the webpage, and also what DOM elemenst we are interested in ...

more info..
Topics : django API
shabda
Comments
Reactions

Essential web-apps to run a software business.

By : shabda

We work on a variety of products and with people. We work in a highly distributed environment, with all of our clients working remotely from us. And while we work out of the same office, we are frequently working from other places as well. Here are the tools which help us stay productive, sane and working. :)

For our open source projects we use Github.
For our client and non OS projects, we use Unfuddle.

For our client code we need both SVN and Git, and we need tickets which can be assigned to people. Both ...

more info..
Topics : business
shabda
Comments
Reactions

Django is not flexible

By : shabda

Django is not flexible at all because you can not do simple things like.

more info..
shabda
Comments
Reactions

Moving home

By : shabda

Tl;dr version:

We are moving our site from Uswaretech.com to Agiliq.com. Please update your book marks and the like.

Longer version:

We have moved. Our new, cool, and amazing site is Agiliq.com. Built with Django, pixie dust and pink unicorns, its is sure to amaze you. Please update your bookmarks.

Gory details:

If you are client of ours, the Unfuddle and billing details would be changing soon. (You should also have received an email from ...

more info..
Topics : meta about
shabda
Comments
Reactions

Rails and Django commands : comparison and conversion

By : shabda

The most commonly used Rails commands and their Django equivalents

Rails | Django

rails console | manage.py shell
rails server | manage.py runserver
rake | None
rails generate | None
rails dbconsole | manage.py dbshell
rails app_name | django-admin.py startproject/manage.py startapp
rake db:create | manage.py syncdb

The salient points to note are,

  1. Django has all commands via manage.py, Rails has it broken into rails and rake.
  2. Overall there are more Rails+Rake commands available than Django commands
  3. There is no one to one mapping between Rails and Django commands. Eg. There are no equivalent to rake doc:* or rake ...

more info..
shabda
Comments
Reactions

The Rails and Django models layer Rosseta stone

By : shabda

Rails Active records and Django models are more similar than they are different. This is a quick guide to converting between Rails 3 and Django 1.2, and is available on github at http://github.com/uswaretech/Acts-as-Django

Defining models

Both Django and Rails keep the canonical database representation in ruby or python.

#Django

class Post(models.Model):
    name = models.CharField(max_length = 100, )
    slug = models.CharField(max_length = 100, )
    body = models.TextField()

class Comments(models.Model):
    post = models.ForeignKey(Post)
    username = models.CharField(max_length = 100, )
    comment = models.TextField()

#Rails

#db/schema.rb
ActiveRecord::Schema.define(:version => 20100319195739) do

  create_table "comments", :force ...

more info..
shabda
Comments
Reactions

Doing things with Django models - aka - Django models tutorial

By : shabda

Django abstracts most of the actions you would be doing with the Database. What it doesn't abstracts, and doesn't try to abstract is the Database modelling part. This is a quick tutorial describing to how model your data in Django models.py, and how to access and modify them.

Consider a hypothetical HR department, which wants you to build an application to track and manage their processes. They have employees who work for a department, contractors who work for multiple department. Let's see how you you would do that in Django.

from django.db import models

class ...

more info..
shabda
Comments
Reactions

Wordpress and Django: best buddies

By : shabda

Summary: How to integrate a non Django database system in your Django code, using Wordpress as example. The completed code is available at github or you can see some screnshots


Though there are quite a few good Django blog applications, our blog is based on Wordpress. A number of plugin's make moving to a Django based app a bad decision for us, and not in the spirit of "best tools for the job".

We moved the other way, and decided to use Django to admin the Wordpress database. The completed code is available on Github

It is not too ...

more info..
shabda
Comments
Reactions

Doing things with Django forms

By : shabda

Forms are one of the best features of Django. (After models, admin, url routing etc :) ). Here is a quick tutorial describing how to do things with Django forms.

  1. Basic form

Prob. You want to show a form, validate it and display it.

Ans. Create a simple form.

class UserForm(forms.Form):
    username = forms.CharField()
    joined_on = forms.DateField()

This wil take care that the form is displayed with two text field, and a value for them are filled in, and the second field has correct formatting for a date.

2.

Prob. Create a form which has values populated depending upon a ...

more info..
shabda
Comments
Reactions

Tools of Pro Django developer - aka What powers dinette and almost every app we write.

By : shabda

There are some tools and apps which we use with almost all apps we write, and in particular which, we used for dinette. Here they are broken into useful during development, and (also) useful post development.

During Development

  1. Ipython and ipdb
  2. South
  3. Django test utils
  4. Django extensions
  5. Django debug toolbar
Ipython and ipdb

Ipython is a enhanced shell for python. Ipdb similarly add extra capacity to the builtin pdb debugger. It is extremely convenient to drop into a ipython shell right where a complex piece of code is being hit.

from IPython.Shell import IPShellEmbed
ipython = IPShellEmbed()
ipython()

Of course ...

more info..
Topics : python tips
shabda
Comments
Reactions

django-forum

By : shabda

twitter ready version:

We have released a Django forum application, with some cool features not in any other Django based forum. You can get it here or see it in action.

blog version

There are quite a few Django based forum applications, so why another? Its a bit of a rhetorical question, as the answer is "none of them met my needs exactly, so we created my own", as you might expect.

Without further ado here is a list of features. It is available on uswaretech.com/forum/.

  • Based on, inspired by and ripped from PunBB. (Thanks!)
  • PunBB like 3 ...

more info..
Topics : django utilities apps
shabda
Comments
Reactions

Django-buzz

By : shabda

We have updated the Django popular stories widget, which powers the widget in the side bar. It is now on Github.

Earlier the code used was hardcoded to only find Django stories, but now you can create arbitary topics from admin.

Get the code and create the widgets on your servers, (or let us know, and we will create it here if it is interesting). We created three we want to track. Databases, Python and Javascript

Databases

Python

Javascript


We build amazing web apps. Talk to us to discuss what we can do for you.

more info..
Topics : Uncategorized
shabda
Comments
Reactions

Django quiz

By : shabda

A quick django quiz. Answers available tomorrow. Get it as a text file (django-quiz) or on google docs or read below.

### Easy

1. You have a class defined as

    class Post(models.Model):
        name = models.CharField(max_length=100)
        is_active = models.BooleanField(default=False)

You create multiple objects of this type. If you do
Post.objects.get(is_active=False),

what exceptions is raised?

a. MultipleObjectsReturned
b. ManyObjectsReturned
c. SyntaxError
d. MultipleModelReturned
e. ManyModelReturned

2. Where is the function render_to_response defined?

a. django.views
b. django.shortcuts
c. django.templates
d. django.contrib.templates
e. django.contrib.shortcuts

3. What is the ...

more info..
Topics : django tips meta
shabda
Comments
Reactions

The magic of metaclasses in Python

By : shabda

Metaclasses are a way for you to have a class act as the template for another class. They are simlar to a classfactory, in that they create new classes. In words of Tim Peters Metaclasses are deeper magic than 99% of people are going to need.

However, in right hands they can be a potent tool, in particular Django uses metaclasses beautifully to create very beautiful declarative models. Without further ado, here is a very simple (and very wrong) metaclass example.

class Z(type):
    def __new__(cls, name, bases, attrs, ):
        print cls, name, bases, attrs

class A(object):
    __metaclass__ = Z ...

more info..
Topics : Uncategorized

Writing your own template loaders

By : shabda

Django has three builtin template loaders which are used to get the templates for rendering.

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)

Writing your template loader is a awfuly easy. It is a callable which

  1. Returns a tuple of (openfile, filename) if it can find the template.
  2. Raise TemplateDoesNotExist if the templates cannot be found.

The simplest template loader can be

from django.template import TemplateDoesNotExist
def load_template_source(template_name, template_dirs=None):
        try:
            return open(template_name).read(), template_name
        except IOError:
            raise TemplateDoesNotExist, template_name

if you put this to your template loaders directory ...

more info..
shabda
Comments
Reactions

Django gotchas

By : shabda

This is announcement about our new work, Django Gotchas, a teeny tiny ebook about commonly occurring gotchas with Django. Here is the readme copied from the project.


Django-gotchas is a collections of gotchas which happen commonly when you are working with Django. They are some errors which I have made commonly or seen others do, these are not the errors which happen because they are hard to reason about, these are those errors which hapen when you close your eyes for a moment when coding.


This is still very much a work in progress, released in the spirit of release ...

more info..
Topics : django book tutorial
shabda
Comments
Reactions

Django-SocialAuth - Login via twitter, facebook, openid, yahoo, google using a single app.

By : shabda

TL;DR version: Here is an app to allow logging in via twitter, facebook, openid, yahoo, google, which should work transparently with Django authentication system. (@login_required, User and other infrastructure work as expected.) Demo and Code.Longer version follow:


We are releasing our new app. Django-Socialauth. This app makes it awfully easy, to allow users to login your site using Yahoo/Google/Twitter/Facebook/Openid. A demo is available here.

This is released under an Attribution Assurance License. A copy of the same is provided included with the code.

After installing this app, you can use @login_required on any view ...

more info..
shabda
Comments
Reactions

A response to Dropping Django

By : shabda

Brandon Bloom yesterday wrote an interesting post titled dropping Django. Despite a lot of hand waving(We needed a pragmatic template language to replace Django's idealistic one.), it raises some valid questions, so here is a solution to some of them.

No support for hierarchical url creation.

The simplest representation of nested urls I can think of is a nested tuple. Lets represent, the urls for a simple app by,

>>> tree_urls = ('', 'list',
...     ('edit/', 'edit', ('auto/', 'edit_auto')),
...     ('^add/', 'add'),
...     ('delete/', 'delete', ('hard/', 'delete_hard'))
...     )

Guess what, urls.py is just a python module which excepts a variable names urlpatterns.

Which means ...

more info..
Topics : django rambling tips
shabda
Comments
Reactions

Django aggregation tutorial

By : shabda

One of the new and most awaited features with Django 1.1 was aggregation. As usual, Django comes with a very comprehensive documentation for this. Here, I have tried to put this in how-to form.

Jump to howtos or Get source on Github.

Essentially, aggregations are nothing but a way to perform an operation on group of rows. In databases, they are represented by operators as sum, avg etc.

To do these operations Django added two new methods to querysets.

  1. aggregate
  2. annotate

When you are have a queryset you can do two operations on it,

  1. Operate over the rowset to ...

more info..
shabda
Comments
Reactions

On Captcha

By : shabda

When building public facing websites, spam is a real problem. Captcha has been teated as the first line of defence aginst this problem. If you must use captcha, here are some best practices working with them.

Can you do without one?

A lot of places captcha's are put to filter spam in user generated comment. One of the largest sources of UGC is comments on wordpress blogs. They do not use a captcha, and instead pass all comments through Akismet to verify which comments are spam, and reject the spams. In many cases, such a system would work for ...

more info..
Topics : tips
shabda
Comments
Reactions

Django design patterns

By : shabda

This is announcement about our new work, Django design patterns, a ebook about, well, Django design patterns. (Well imagine that!). Here is the readme copied from there.


[Edit] Syntax highlighting and indentation preservation were totally brroken. Fixed now.


Django design patterns is a book about commonly occuring patterns in Django. Not patterns in Gof sense, but patterns in the sense, we work this way, and it works for us. For us it is a ~pattern of work~ sense.

At this point this is just a lot of brain dump from us.

The latest sources are always available from http://github ...

more info..
Topics : django tips book

Remote debugging - debugging pesky server only bugs

By : shabda

Here is a quick tip. (Obvious if you work with Django for any length of time, but I have seen a few people who are not aware)

You can put debug trace import pdb; pdb.set_trace() in your code, and put it on the server. When you access this view from your local browser, the debug is still hit and you have a debug shell on your server where you can step through. (Obviously this works only if you ran the code via manage.py runserver. But manage.py runserver start the server to listen only on local connections. If ...

more info..
Topics : django tips
shabda
Comments
Reactions

Django Request Response processing

By : shabda

Have you wondered the steps a users request goes through before being responded to by Django? The answer lies in reading django.core.handlers.base and django.core.handlers.wsgi. Here is a diagram explaining what happens. (Click to enlarge.)

The steps are. (With Apache/Mod_wsgi, similar steps for other setup.)

  1. User's request comes to Apache etc.
  2. Apache sends request to django.core.handlers.wsgi via mod_wsgi.
  3. A list of request and response middleware callables is created.
  4. Request middleware is applied. If it sends a response, it is returned to the user.
  5. urlresolvers.resolve finds the view funcion to ...

more info..
Topics : django tips
shabda
Comments
Reactions

Understanding decorators

By : shabda

If you used Django for any length of time, you would have come across the login_required decorator. You write @login_required before a view, and it magically becomes accessible only to authenticated users.

Decorators were introduced in python 2.4. PEP 318 is the PEP describing it. At the simplest decorators are nothing but callables returning other callables, and the decorator syntax @decorator is nothing but foo = bar(foo), where both bar and foo are callables.

Let us see some decorators in action.

In [1]: def good_function():
   ...:     print 'I am a good function'
   ...:     
   ...:

In [2]: def decorator(orig_func):
   ...:     def bad_func():
   ...:         print ...

more info..
Topics : python tips
shabda
Comments
Reactions

Generating pseudo random text with Markov chains using Python

By : shabda

First the definition from Wolfram

A Markov chain is collection of random variables {X_t} (where the index t runs through 0, 1, ...) having the property that, given the present, the future is conditionally independent of the past.

Wikipedia is a little clearer

...Markov chain is a stochastic process with markov property ... [Which means] state changes are probabilistic, and future state depend on current state only.

Markov chains have various uses, but now let's see how it can be used to generate gibberish, which might look legit.

The algorithm is,

  1. Have a text which will serve as the corpus from ...

more info..
Topics : seo algorithms

Django-subdomains - Easily create subscription based subdomains enabled webapps

By : shabda

A common goal in web application development is creating subscription based application, where users can use their domains.

For example,
1. Basecamp allows you to manage your project, and gives users as subdomain like xyz.grouphub.com 2. Blogger goes a step further, and allows you to use arbitrary domains with your domain, using Cnames.

django-subdomains is an application which makes both these possible, and allows you to charge the users using paypal.

More details are available here, but to whet your appetite, some details


  1. You want to allow users to create accounts.
  2. Users should get a subdomain for their ...

more info..

Web development companies working with Django

By : shabda

At Agiliq, we work with some of the best web development agencies. I wanted a list of the other building web applications with Django, here is such a list, in no specific order.

  1. Additional View Tasmania, Australia
  2. Lincolnloop Colorado, USA
  3. EnzymeIt Hong Kong and Australia
  4. Illusion Factory California, USA
  5. Zigzap Technologies Cincinnati, USA
  6. Torchbox Oxfordshire, UK
  7. Liberiun Brazil
  8. Yed-Prior Now known as Djangostars Ukraine
  9. Tatum Interactive New York, USA
  10. Menttes Argentina
  11. Tarams Bangalore, India
  12. Cubedroot Ireland

And of course Agiliq

Additions:

  1. Adoleo Texas, USA
  2. Siu Design United Kingdom
  3. Web Collective Seattle, USA
  4. Digital Eternal Malaysia
  5. Revolution Systems Lawrence, Kansas, USA ...

more info..
Topics : business

Developing a Web Application Live in 15 min, in django framework

By : shabda

Here is the presentation which Lakshman presented at Bar Camp Banglore, where he created a Web application(simple forum), and got to audience to complete the forum with him live.

more info..
Topics : presentations
shabda
Comments
Reactions

Constraint programming in Python

By : shabda

Imagine this, you want to solve a problem, the algorithm for which you do not know. You just know the problem.

From wikipedia,
Constraints differ from the common primitives of imperative programming languages in that they do not specify a step or sequence of steps to execute, but rather the properties of a solution to be found.

Assume that there exists an alternate world where you only need to specify the problem, the computer will find out an algorithm to find it, even better if could you write it in Python.

Stop assuming it hapens every day, and this is ...

more info..
Topics : algorithms
shabda
Comments
Reactions

Django with Mysql and Apache on EC2

By : shabda

What is EC2

Unless you have been living on Mars these last few years, you are sure to have heard of EC2. Amazon's cloud offering, it offers infinite scalability. Using EC2, you can bring up any number of machines online at minutes notice, and after you are done with them, bring them down.

How does EC2 work?

A EC2 machine is nothing but a bare machine. An Amazon Machine Image (AMI) is a machine bundled as an Image, with preconfigured software which you can start at moments notice. We will take a AMI with a basic Ubuntu installed, and ...

more info..
Topics : web2.0 Amazon
shabda
Comments
Reactions

How to build a Facebook app in Django

By : shabda

Facebook has a simple and robust API which allows users to build applications for the Facebook platform. We being the intelligent developers will use the superb Django framework to build our application.

The completed code for this is available at https://svn.uswaretech.com/favlang/. The completed application is deployed to facebook here.

How does a Facebook application work?

  1. The users make a request to apps.facebook.com/yourapp/page1/
  2. The Facebook servers make a request to yourserver.com/page1/
  3. You get the requests and can make calls to Facebook API, and use FQL to query the Facebook tables.
  4. You ...

more info..
Topics : facebook

Using Paypal with Django

By : shabda

Paypal has a comprehensive API to use their services programatically. The ExpressCheckout API allows you to get the user's details and then process the payments on your servers. They include a SOAP and NVP API. With NVP you do a GET to the Paypal servers with Url encoded values, get responses in plain text and work with them.

The basic flow for ExpressCheckout is something like this,

  1. You make a SetExpressCheckout request to Paypal, passing your credentials and and the amount you want to charge etc.
  2. Paypal returns an response with ACK of SUCCESS and token which you need ...

more info..
Topics : tips paypal

Building reusable Django apps

By : shabda

Recently I updated a lot of our old apps to be compatible with Django 1.0 and be reusable. Before we go further, let me define a _ Reusable Django App _.

A Django app is reusable if

*  It is app. (That is, it is not a project, and has no settings.py/manage.py.)
* It can be dropped in an existing project, and only places where the project should need editing are `settings.py` `installed_apps` and the projects level `urls.py`.
* It can be used in the project with an arbitrary url prefix.

The updated apps were written initially ...

more info..
Topics : tips

Using subdomains with Django

By : shabda

Django makes using beautiful urls a snap. However using subdomains with Django is not so obvious. Here is an article explaining this.

Advantages of subdomain

  1. Sometimes looks more professional. Users will prefer someblog.wordpress.com over wordpress.com/someblog.
  2. If each part of your site is Under a different untrusted users, you might want to give them a separate subdomain, so that if they do Blackhat Seo on their part, the main site is not harmed.
  3. Your users can point a Cname to their subdomain to use domain of their choice with their subdomain.

Disadvantages of subdomain

  1. When you need ...

more info..
Topics : tips

Dynamic forms with Django

By : shabda

Newforms, (or forms now) are without doubt one of the coolest features of Django. (Of course after Admin, Localflavor, and many others). Here is some sample code.

class EmployeeForm(forms.Form):
    name = forms.CharField()
    age = forms.IntegerField()
    resume = forms.FileField()

Just this code gives you

  1. A form which knows how to render itself as Html.
  2. A form which knows how to validate data on the server side.
  3. A form which knows how to show the relevant errors.

However think of this scenario,

You need to customise your form depending on values in the Database.

What you want to do is ...

more info..
Topics : tips forms

Generating PDFs with Django

By : shabda

If your web app creates report chances are you also want this report in PDF form. The Django docs describe a way to generate PDFs using ReportLab. Here is some code from there.

from reportlab.pdfgen import canvas
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

    # Create the PDF object, using the response object as its "file."
    p = canvas.Canvas(response)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full ...

more info..
Topics : tips

Building SEO optimised Django web applications

By : shabda

This is an article about building SEO, optmised web applications with Django. I assume you already have an idea how Seo works. We will take the example of a hypothetical Blog app to explain the suggestions made.

Without further ado, here are the tips.

Basic

  1. Use beautiful URLs.
  2. Learn the difference between HTTP 301 and HTTP 302 redirects.
  3. Layout content in a SEO friendly way.
  4. Create a sitmaps.

Not so obvious

  1. Use the Admin to allow end users to update fields.
  2. Do not get your Url structures too deep.
  3. Create a robots.txt file.
  4. Link to your pages wisely.
  5. Minimise ...

more info..
Topics : seo

An Interview with Adrian Holovaty - Creator of Django

By : shabda

Adrian Holovaty is the co-creator of Django, author of the Django book and is currently the BDFL of Django along with Jacob Kaplan-Moss. He studied journalism at University of Missouri–Columbia and has worked with many news sites including Lawrence Journal World and Washington Post. He currently works at EveryBlock, a startup he founded.


Shabda: Would you tell a little about yourself? You majored in Journalism, how did you move to Programming?

Adrian: Sure! I have a dual background in journalism and computer science. I intended to get a degree in journalism and a minor in computer science, but things ...

more info..

An Interview with Jacob Kaplan-Moss - Creator of Django

By : shabda

Jacob Kaplan-Moss Jacob Kaplan-Moss is the co-creator of Django along with Adrian Holovaty, as well as the author of the Django Book. He has been involved with Django since before it was called Django. He is currently employed at Whiskey Media where his job is hacking at Django. He blogs on Jacobian.org. He graciously agreed to be interviewed at the 42topics blog.


Shabda: Would you tell a little about yourself? How did you get started with Django? What other software/applications have you worked with. (Both OSS and otherwise)?

Jacob: So a bit about me: I grew up in Silicon Valley ...

more info..

An idea a day - A geographical wiki

By : shabda

This is an article in the Five Startup Ideas series at the 42topics blog. In his essay, Ideas for Startups, Paul Graham argues that ideas are not a critical factor for success of startups. Although I do not believe that ideas are worthless, as many people do, I believe that they are not any where near as important as execution. So to prove my point, I am giving away 5 startup ideas in next five days. All of them describe a problem, its solution, the technology involved, the competition and market size. If you are not a hacker, and want ...

more info..

An idea a day - Alternative to GAE

By : shabda

This is an article in the Five Startup Ideas series at the 42topics blog. In his essay, Ideas for Startups, Paul Graham argues that ideas are not a critical factor for success of startups. Although I do not believe that ideas are worthless, as many people do, I believe that they are not any where near as important as execution. So to prove my point, I am giving away 5 startup ideas in next five days. All of them describe a problem, its solution, the technology involved, the competition and market size. If you are not a hacker, and want ...

more info..

An idea a day - Remotely hosted Analytics solution

By : shabda

This is an article in the Five Startup Ideas series at the 42topics blog. In his essay, Ideas for Startups, Paul Graham argues that ideas are not a critical factor for success of startups. Although I do not believe that ideas are worthless, as many people do, I believe that they are not any where near as important as execution. So to prove my point, I am giving away 5 startup ideas in next five days. All of them describe a problem, its solution, the technology involved, the competition and market size. If you are not a hacker, and want ...

more info..

Popularising Django - Part 2

By : shabda

If you would have read my Popularizing Django post, you might know that I consider building a killer packaged app to be the best way to popularize Django. This is a post about what that app must be.

For PHP it was Wordpress and PhpBB. Both were free, very easy to install and came with every thing packaged. If you have followed the history of either you must know that they have always been plagued by security problems. Assertion: Most users, even programmers, value ease of use and install over technical superiority. Case in point, Windows vs Linux.

For Rails ...

more info..
Topics : Uncategorized

An idea a day - Recomendation system based ad network

By : shabda

This is an article in the Five Startup Ideas series at the 42topics blog. In his essay, Ideas for Startups, Paul Graham argues that ideas are not a critical factor for success of startups. Although I do not believe that ideas are worthless, as many people do, I believe that they are not any where near as important as execution. So to prove my point, I am giving away 5 startup ideas in next five days. All of them describe a problem, its solution, the technology involved, the competition and market size. If you are not a hacker, and want ...

more info..

An idea a day - An automated Adwords optimizer

By : shabda

This is an article in the Five Startup Ideas series at the 42topics blog. In his essay, Ideas for Startups, Paul Graham argues that ideas are not a critical factor for success of startups. Although I do not believe that ideas are worthless, as many people do, I believe that they are not any where near as important as execution. So to prove my point, I am giving away 5 startup ideas in next five days. All of them describe a problem, its solution, the technology involved, the competition and market size. If you are not a hacker, and want ...

more info..

Parable of the single sheep - Or How Google is destroying the internet, and nobody seems to know.

By : shabda

This is a parable in two parts. Story and the Moral. If you are in a hurry you might want to skip ahead to the moral (But you miss the beautiful story).

The Story

Long ago was the kingdom of Foobr, a kingdom mostly of shepherds, who grazed their sheep under the benevolent but watchful eyes of their King Oggle. There were all types of shepherds in the kingdom, some had only a few sheep, and some had a few hundreds. The sheep too were of all types and varieties, some gave a ton of wool, and some only a ...

more info..

An interview with Michael Trier

By : shabda

Michael Trier is a long time Django user and evangelist. He has worked with a number of technologies including Rails and .net. His insights on marketing Django to traditionally Enterprisy areas were extremely informative. He produces TWiD, along with Brian Rosner which is great to keep abreast of the latest happenings in the Django community. He graciously agreed to be interviewed by the 42topics blog.


Shabda: Would you tell a little about yourself, how did you get started with Django, what other projects have you used or are associated with?

Michael: Well, I've been programming ever since I can ...

more info..
Topics : django marketing

Popularizing Django -- Or Reusable apps considered harmful.

By : shabda

For all its technical merits, Django is still a very niche technology. It is my belief that the thing which is holding Django back the most, is due to one of its strengths.

Making reusable apps is easy and simple in Django. In Django this is the correct way to do things. You take a few apps, mix them together in your project, and deploy to start your site.

Compare the installation steps of Wordpress and an imaginary blog software better than Wordpress called Djangopress.

Wordpress

  1. FTP wordpress to webserver.
  2. Point browser to site.com/blog
  3. Next-Next-Next done.

Djangopress

  1. Svn ...

more info..
Topics : django marketing

Interview with Bob Massa - Internet marketing for technology startups

By : shabda

Bob Massa is a pioneer in the field of Internet marketing. He has been working on Internet Marketing and Search Engine Placement since 1997. He has operated Magic-city.net and SearchKing. He gained both fame and notoriety when he sued Google, which is a classic case study in PR stunts. We talked about the importance of SEO and Marketing for startups. More information about him can be had at bobmassa.com or his blog at Ask the SEO guru.


Shabda: Would you tell us a little about yourself. How did you get started with SEO and Internet Marketing? What is ...

more info..

An interview with Russell Keith-Magee - Django core contributor

By : shabda

Russell Keith-Magee is a longtime core contributor to Django. He has worked extensively with the Django testing and serialization components. He is currently working on django-evolution, the ability to do schema evolution from Django, an often requested feature, and is mentoring a GSOC proposal to add aggregate queries support to Django ORM. He is currently a Senior R&D Software Engineer at plugger.com.au. He graciously agreed to an email interview with the 42topics blog.


Shabda: Would you tell a little about yourself? How did you get started with Django? What areas of Django have you contributed to?

Russell ...

more info..
Topics : django interviews

Parable of the Captcha - The futility of fighting automated spam with automated methods.

By : shabda

(A story about Captcha, and why they do more bad than good. You may also like Parable of the Nowfollow)

Part 1: Captcha and Spammers

In a time not so long ago, and not so far off existed a country called Theweb. It was a well populated place, populated with upstanding citizens who called themselves Webpage, and lived together in harmony.

For long there was no conflict in Theweb, but where happiness resides can evil be the far behind? The evil S.P.Ammers infiltrated Theweb. They were able to bend a Webpage to do their bidding.

Of course the ...

more info..
Topics : search

Interview with James Bennett - Django release manager

By : shabda

James Bennett is the release manager of Django, and a long time contributor. He works on Ellington, a CMS designed for news organizations. His book, Practical Django Projects, is being published by Apress, and is scheduled to hit bookshelves in June 2008. He graciously agreed to be interviewed at the 42topics.com blog. His blog, The B-List, can be found here.

Shabda: Would you tell something about yourself, how did you get started with Django, and what other OSS projects are you involved with?

James: I got into Django fairly soon after the initial public release; I'd been doing ...

more info..
Topics : django interviews

An interview with Malcolm Tredinnick - Django core contributor

By : shabda

Malcolm Tredinnick is a core contributor to Django, and was the driving force behind the Queryset-refactor branch of Django, which adds important capabilities such as model inheritance. He has a long association with OSS, and contributed significantly to GNOME and Django. He graciously agreed to be interviewed at 42topics blog. Malcolm's blog, Defying Classification, can be read here.

Shabda: Would you tell a few things about yourself, how did you get involved with OSS and Gnome, and with Django?

Malcolm: Here are some recollections I've written about: 1 and 2 Short version; started using Linux in university as ...

more info..
Topics : django interviews

Why people start startups.

By : shabda

In the glorious tradition of the internet, where we generalize from way too little data, I am going to tell you exactly why people start startups. Of course, I have no experience, on why people make this trade of security for adventure, apart from my own, and a few other very early stage startups. So yes, this is a personal story. This is why I, and everyone I know started a startup.

“If you want to build a ship, don’t drum up the men to gather wood, divide the work and give orders. Instead, teach them to yearn ...

more info..

Marketing lessons from Google

By : shabda

Widely respected for their engineering talent, and amazing hacker culture, Google is never credited for the amazing marketing they do. When we look for the companies which have done a great job at marketing/branding, we think of Guiness, Apple, or Ikea. Today I want to talk about the marketing lessons we can learn from Google.

It is all about the ROI.

For Barcamp Hyderbad, Google let us use its offices. They generally let you use their premises for hacker events. Let us calculate the ROI for Google for allowing this event.

This event was on Saturday, so cost of ...

more info..
Topics : google marketing

Five things I love about Django.

By : shabda

I posted five things I hate about Django, so as a penance, I will of course have to tell the "Five things I love about Django".

The Admin interface rocks:

I have demoed Django to a fair number of People, and when you write a few lines in models.py, and then show the auto generated Admin interface, this is a jaw-dropping moment. Happened with me every time I introduced Django to someone. In Barcamp Hyderabad 05, people could not believe this was so easy, and asked if there was some more code behind this.

Of course Admin is much ...

more info..
Topics : Uncategorized

Five Things I Hate About Django.

By : shabda

The five things I hate about * meme seems have died down, and memes, should not be allowed to die.

Of course I love Django, and have bet very heavily on it. But we do not know a topic, until we know it warts, so here you go. The listing is in no particular order, so sorry no numbering.

Ajax with Django is hard:

Most of the Django Community has decided that bundling Javascript helpers with a python framework is bad idea. Though I can understand the reasoning, (argued here and rebuttal), that Javascript is so basic that you can not ...

more info..
Topics : django python

New tutorial - Building a search engine with Appengine and Yahoo

By : shabda

I wrote a new tutorial on building a search engine using Appengine, and Yahoo Search API here. This uses pure Appengine API, and not Django, and is a tutorial on how to use Appengine without Django.

more info..

First step to startup - Getting your pitch

By : shabda

With launch of Google Appengine, there has never been a better time to start a startup. Let not the lack of a business plan or a pitch hold you back. Go to our web 2.0 startup pitch generator, and get your own, custom, startup pitch. Hurry only 24192 available.

The original source for this was written by Nathan and was in Perl. Of course we needed a web2.0 logo for such a marvelous piece of code. This comes from web2.0 logo generator.

The source for this is available here

more info..
Topics : python satire startup

Two Django+Appengine Tutorials

By : shabda

I have posted two Tutorials for Using Django with Appengine.

And here a few good links about the topic.

  • James Bennet tells exactly why Appengine and Django are not so good together.
  • Ian Bicking has an interesting take on how Appengine can change the economics of Python hosting.
  • The guys at Joyent reading my mind on why I or you can not deploy any production site on Appengine. (Hint. you mean I can never move away, without writing half my ...

more info..

Using Appengine with Django, why it is pretty much unusable

By : shabda

We are hard at work building 42topics.com, and are looking at the best places to deploy this. So when I heard about Appengine, with out of box Django support(gasp!) I was delighted. After using it for a day, and posting a tutorial, I am so disappointed.

Peeves in no particular order.

  • Appengine is a very constrained environment, so out goes any chance to run background jobs.
  • The ORM-API is very similar to Django, but yet the Django API is much better. modelobj.filter('attr =', value1).filter('attr2 =', value2) or modelobj.filter(attr = value1, attr2 = value2). Putting entity level ...

more info..

Google Appengine - First Impressions

By : shabda

Google launched their EC2 competitor, Appengine yesterday, and all hell broke loose. And in about 24 hours, the 10,000 accounts were used up. Currently it is tied to only working with python, and Django 0.96.1 works out of the box. <!- - more - ->

The Good

  • Python powered. Django works out of the box.
  • No sysadmining chores.
  • Promise of infinite scalability with no configuration. (Ah!)
  • Free for now.

The Bad

  • Python powered, if you want to use ruby/java/php, sorry you are out of luck.
  • Your code is tied to Google. You might be able to reuse most of ...

more info..
©COPYRIGHT AGILIQ SOLUTIONS