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

Getting started with South for Django DB migrations

By : akshar

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

Behind the Scenes: Request to Response

By : thejaswi

In the previous installment of "Behind the Scenes", we saw how the control flows from Form to File Storage. Today, we are going to see how the application reacts from request to response.

In this post, we are going to assume that we are using django's inbuilt runserver. The flow doesn't change much for other WSGI servers available.

When you invoke the runserver management command, the command line options are validated and an instance of WSGIServer is created and passed the WSGIRequestHandler, which is used to create the request object (WSGIRequest). After the request object is created and ...

more info..

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

Behind the Scenes: From HTML Form to Storage

By : thejaswi

In this post, we are going to see what happens behind the scenes when a file is uploaded to a django powered web application.

File Upload Flow

An HTML form with a file input (atleast one) and encoding set to multipart/form-data is submitted. The MultiPartParser parses the POST request and returns a tuple of the POST and FILES data (request.POST, request.FILES). The MultiPartParser processes the uploaded data using the File Upload Handlers objects (through the new_file, receive_data_chunk and upload_complete methods). The request.FILES values are a sequence of instances of UploadedFile.

In the django form, we pass the request.FILES ...

more info..
Topics : django files upload
Javed
Comments
Reactions

Real time applications with Django, XMPP and StropheJS

By : Javed

TL;DR:

Introduction:

PubSub is a XMPP extension which allows publishing and subscribing to events. This is useful when you instantly want to notify many clients about something interesting happening on your server.

Quoting the authors of PubSub specs:

The protocol enables XMPP entities to create nodes (topics) at a
pubsub service and publish information at those nodes; an event
notification (with or without payload) is then broadcasted to all ...

more info..
Javed
Comments
Reactions

Seven reasons why you should switch to Vim

By : Javed

So you want a better IDE for developing django, huh? Why not give good old vim a try?

Use pathogen to maintain your vim plugins (and sanity). Using this, you can clone the repositories listed here to .vim/bundle/ and start using them right away.

Also, consider adding your .vimrc and .vim to a repository. Include .vimrc inside .vim and symlink .vim/.vimrc to ~/.vimrc to version control your .vimrc.

My vim files can be found here. Also, here's an imgur album demonstrating these plugins in action.

1. Syntax highlighting for django templates

Starting from vim 7.1, syntax ...

more info..
Topics : django vim

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

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

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

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

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
lakshman
Comments
Reactions

Using bpython shell with django (and some Ipython features you should know)

By : lakshman

What is bpython?

bpython is a fancy interface to the Python interpreter for Unix-like operating system.

says the bpython home page. It provides syntax highlighting, auto completion, auto-indentation and such stuff.

Unlike iPython, which implements then entire shell functions and emulates the standard python shell, and adds enhancements, bpython just adds features on top of the existing python shell functionality, using the curses module.

bpython

The "killer feature" of bpython is, as you can see from the image above, the IDE like prompting of the function parameters and the doc string of the function dynamically. I have always thought, what IntellijIDEA ...

more info..
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
ashok
Comments
Reactions

Django for a Rails Developer

By : ashok

This is not yet another Django vs Rails blog post. It is a compilation of notes I made working with Django after having worked on Rails for years.

In this post I want to give a brief introduction to Django project layout from a Rails developer point of view, on what is there, what is not there and where to look for things. It should help a rails developer working on django be able to find the necessary files and underatnd the layout of the project files.

Once you have both the frameworks installed on your system you can create ...

more info..
Topics : rails django python

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..
rohit
Comments
Reactions

Aren't django signals a little like comefrom?

By : rohit


In computer programming, COMEFROM (or COME FROM) is an obscure control flow
structure used in some programming languages, primarily as a joke.

I never liked using signals. Recently I was asked that, and has no answer, but a little thinking led me to this question. Aren't signals a little like COMEFROM. If yes, aren't they as bad as COMEFROM? If you do not know what a COMEFROM is, [wikipedia to the rescue](http://en.wikipedia.org/wiki/COMEFROM)

Some hypothetical code using COMEFROM, again from wikipedia,

from goto import comefrom, label
comefrom .repeat
name = raw_input('what is your ...

more info..
Topics : django rambling
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
lakshman
Comments
Reactions

Better Python package management using source and version control systems

By : lakshman

Thanks to awesome django community, there is plenty of open source django code around.

These packages get updated quite often and if you use it often like we do, you'd have possibly realized the need to manage these packages better.

Thankfully, all python ever needs is the source, and all you need to do is to place the source in the python path.

Most projects use Distributed Version Control Systems like Mercurial and Git, and they come locally with the entire history of the source which provides a lot of control to use any version of the code. For ...

more info..
lakshman
Comments
Reactions

Develop Twitter API application in django and deploy on Google App Engine

By : lakshman

Twitter's robust REST API enables building of good applications that leverage its increasingly large and real-time data.

Google's cloud system App Engine not only provides a scalable platform for deploying applications, but also proves to be economically viable because of its pay per resource usage model and a large free quota.

Little wonder then, there are increasingly large number of twitter apps being deployed on App Engine.

In this post, I am going to examine how to create a simple application based on twitter's REST API and deploy it on Google App Engine. A deployed version can ...

more info..

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 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

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

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

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..

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