Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Python Decorators for Djangonauts
If you’ve used Django for any amount of time then you’ve probably come across decorators. They’re the things with the @ signs over the top of your view. The first one you’re likely to see is the @login_required decorator, which requires a user to be logged in before the view will run. If they are [...] -
Autocomplete for Foreign Keys in the Django Admin Explained
When the select drop-down for foreign keys in the Django Admin gets big it can become a usability issue. One solution is to create a custom UI for the the model, but stretching the Django Admin to the limit is one of the fun parts of working with Django. Prior Art The top hit on Google is django-autocomplete. This project is the basis of my approach and therefore much thanks goes to the author. There hasn't been an update since early 2009 and I wasn't able to get it working without a lot of changes. The changes evolved into what I consider a better approach. Another interesting project is django-ajax-selects which is very fancy, complicated looking and actively maintained. It allows for very pretty autocompletes. My solution does it without any AJAX so it is a bit easier to use and makes for an easier case study. An AJAX based solution solves another critical problem: the drop down being so large it takes a long time for the admin page to render. Raw id fields also help to solve this problem albeit in a less elegant way. There are a few other projects, some using YUI, some focusing on many … -
Adding GDirections support to GeoDjango Google Maps
I came across the necessity of drawing directions in a google map using GeoDjango API. But gmap.py doesn’t come with GDirections support built-in in Django 1.2.1. So I decided to add it and fill a ticket with a patch This adds a GDirections wrapper, that is controlled in a directions variable in the GoogleMap object. Of course the google-map.js had to be modified. These are my first 2 cents to GeoDjango project, which I consider a complete other framework apart from Django, that shares structure and philosophy. -
Scaffolding template tags for Django forms
We love Django here at Isotoma, and we love using Django’s awesome form classes to generate self-generating, self-validating, [X]HTML forms. However, in practically every new Django project I find myself doing the same thing over and over again (and I know others do too): breaking the display of a Django form instance up into individual fields, with appropriate mark-up wrappers. Effectively I keep recreating the output of BaseForm.as_p/as_ul/as_table with template tags and mark-up. For example, outputting a login form, rather than doing: {{ form.as_p }} We would do: <p> {% if form.username.errors %} {% for error in form.username.errors %} {{ error }} {% endfor %} {% endif %} {{ form.username.label }} {{ form.username }} </p> <p> {% if form.password.errors %} {% for error in form.password.errors %} {{ error }} {% endfor %} {% endif %} {{ form.password.label }} {{ form.password }} </p> Why would you want to do this? There are several reasons, but generally it’s to apply custom mark-up to a particular element (notice I said mark-up, not styling, that can be done with the generated field IDs), as well as completely customising the output of the form (using <div>‘s instead etc.), and also because some designers tend to … -
Get SQL features on NoSQL with django-dbindexer
With the just released django-dbindexer you can use all Django lookup types ("iexact", "month", "day", etc.) on non-relational DBs like App Engine and MongoDB, even if they're not natively supported by that DB! Also, django-dbindexer can help you with optimizing your code. For instance, case-insensitive filters on MongoDB can't use indexes, so they're not very efficient. With django-dbindexer they can be handled as efficient case-sensitive filters which utilize an index. Sounds too good to be true? Keep reading. Non-relational databases have rather limited query APIs. For example, on App Engine you can't do a case-insensitive "iexact" match. Developers on these platforms have to use ugly workarounds to implement unsupported filters. Poor guys. ;) This is how you'd emulate "iexact" and "month" on App Engine (using djangoappengine): # models.py: class MyModel(models.Model): name = models.CharField(max_length=64) lowercase_name = models.CharField(max_length=64, editable=False) last_modified = models.DateTimeField(auto_now=True) month_last_modified = models.IntegerField(editable=False) def save(self, *args, **kwargs): self.lowercase_name = self.name.lower() self.month_last_modified = self.last_modified.month super(MyModel, self).save(*args, **kwargs) def run_query(name, month): MyModel.objects.filter(lowercase_name=name.lower(), month_last_modified=month) This has several problems: You have to remember to use lowercase_name and lower() and month_last_modified You can't reuse existing Django code without analyzing and modifying all models and queries You can't easily utilize this workaround in the admin interface … -
I Am Discontinuing Telvee
Telvee was originally a Facebook app. It was Burak Büyükdemir‘s idea to create a virtual coffee reading app. Rakı Sofrası was super popular then. We have quickly built and deployed and getting some good results. But the competition wasn’t fair. When I decided to give this software a fair chance to succeed on its very [...] -
Person X is...
Many years ago when I was at ActiveState we had a new manager, I got one of those every month or so it wasn't a big deal. One of the things he said was - he would never use the excuse that a decision will be made because person X said so and they know best. It was 9 years ago, so I can't remember the exact wording. What he was saying is that all decisions can be questioned, things need to be explained and we shouldn't be just blindly following some people. He was also saying that this is bit of elitism, putting other people down. This came back to me a few times as a manager when I made decisions and was questioned. But it really hit me home in slightly different circumstances on the Django mailing lists - and I will point out, this is a rare exception. I've seen at a couple of times people say something like: "our code was written by X, so i doubt there's a bug there", "this was designed by X who has quite a reputation...". Each time, it's felt a bit like the "person X knows best" card has been … -
Django Admin: Making fields read-only for editing
Sometimes, when you are developing a Django website, you want to use the Django admin interface to create and edit your custom, homemade models. How to do this, is well documented on this page on the Django website. However, sometimes you want the edit page to differ from the create page. For example, you might want users to be able to fill in a slug field for a model, but because you are afraid of broken links, you don't want them to be able to edit that slug.Of course you can override the model's save method to raise an exception when somebody tries to edit the slug, but that is both ugly and confusing for the user. What you actually want is a standard text field when you create an object, but a read-only field if you edit an object. From the previously mentioned page, we know that Django supports something called 'readonly_fields' and that the ModelAdmin model has a method called 'get_readonly_fields'. How can we use this information to make a field read-only in edit mode? Simply override the get_readonly_fields method.A silly example:Let's say we have a model called Message, for which we create an admin model called MessageAdmin, … -
Django Simple Captcha et tout devient si simple
Comme d'habitude le mois d'aout fut une vraie folie. Et qui dit mois de folie dit, billet qui prennent du retard. Heureusement que j'ai pu tricher en publiant la première interview. (ben oui c'est beaucoup plus rapide de poser des questions que d'y répondre, enfin beaucoup plus rapide d'écrire les questions dans un mails ... -
Generic relationships in Django
"Last week I’ve completed an interesting task within our project: building internal link-shortening system based on persisted objects, not on constant URLs. The main requirement was to get as loosely-coupled design as possible. In the perfect world the “shortenable” classes should know absolutely nothing about link-shortening mechanism. How to get such a flexibility in Django? I’ve used the ContentTypes framework with generic relations and it works pretty well!" by Marcin Swierczynski -
Permissions with Django-nonrel
Quick update: Florian Hahn has implemented a solution for permission handling with Django on non-relational databases. Django's own permission system unfortunately requires JOIN support and thus doesn't work. After his original announcement the code has been optimized, so a permission check can be done with just two database operations. Also, his backend now scales with the number of users. Florian has posted installation and usage instructions on his blog. Check it out if you need permission support in your project. Leave a comment -
Another nashvegas Update
So something that has been bugging me since the recent release of nashvegas was the lack of handling errors in migration scripts. There were several issues impeding me being able to handle errant scripts gracefully, by which I mean reporting the error via a sys.exit() call. I was sub-shelling to manage.py dbshell where I would PIPE the contents of the script to stdin. Turns out that dbshell executes the database client process via os.execvp which as the Python document states: These functions all execute a new program, replacing the current process; they do not return. So, obviously, I was not going to get a return code from the underlying call, that I might check and take evasive action. Because I was getting to the database client indirectly through dbshell, I was unable to control things like setting flags or variables to control the behavior of the database client. So, even if I were to somehow get around the first problem of os.execvp being used, I still would not be able to set the necessary flags needed to get the client to behave how I wanted it to. Therefore, I decided that I'd just copy the argument building from each of … -
Another nashvegas Update
So something that has been bugging me since the recent release of nashvegas was the lack of handling errors in migration scripts. There were several issues impeding me being able to handle errant scripts gracefully, by which I mean reporting the error via a sys.exit() call. I was sub-shelling to manage.py dbshell where I would PIPE the contents of the script to stdin. Turns out that dbshell executes the database client process via os.execvp which as the Python document states: These functions all execute a new program, replacing the current process; they do not return. So, obviously, I was not going to get a return code from the underlying call, that I might check and take evasive action. Because I was getting to the database client indirectly through dbshell, I was unable to control things like setting flags or variables to control the behavior of the database client. So, even if I were to somehow get around the first problem of os.execvp being used, I still would not be able to set the necessary flags needed to get the client to behave how I wanted it to. Therefore, I decided that I'd just copy the argument building from each of … -
Another nashvegas Update
So something that has been bugging me since the recent release of nashvegas was the lack of handling errors in migration scripts. There were several issues impeding me being able to handle errant scripts gracefully, by which I mean reporting the error via a sys.exit() call. I was sub-shelling to manage.py dbshell where I would PIPE the contents of the script to stdin. Turns out that dbshell executes the database client process via os.execvp which as the Python document states: These functions all execute a new program, replacing the current process; they do not return. So, obviously, I was not going to get a return code from the underlying call, that I might check and take evasive action. Because I was getting to the database client indirectly through dbshell, I was unable to control things like setting flags or variables to control the behavior of the database client. So, even if I were to somehow get around the first problem of os.execvp being used, I still would not be able to set the necessary flags needed to get the client to behave how I wanted it to. Therefore, I decided that I'd just copy the argument building from each of … -
from zope import django: persistence
Having recently come from the Plone world to join Mozilla, I am in the delicious but fleeting position to compare two major Python web frameworks with some pretension of familiarity. Through a series of articles focusing on specific features, I will compare the Zope family of frameworks (as they are used in Plone) with the Django framework, which is gaining popularity at Mozilla and currently runs support.mozilla.com and addons.mozilla.com. -
from zope import django: persistence
Having recently come from the Plone world to join Mozilla, I am in the delicious but fleeting position to compare two major Python web frameworks with some pretension of familiarity. Through a series of articles focusing on specific features, I will compare the Zope family of frameworks (as they are used in Plone) with the Django framework, which is gaining popularity at Mozilla and currently runs support.mozilla.com and addons.mozilla.com. -
Organising your Django code
There are several options when it comes to organising your code in a Django project. There isn’t a ‘correct’ way, and it will depend on the size of the project, if it is a team development, or purely the preference of the developer. Templates Django gives you the ability to put your templates anywhere, either [...] -
A different kind of URL shortener
Today I'm launching my first Google App Engine site. While I built it largely to play with GAE, it is also useful in its own right (I like to think so anyway). It does two different things: Link shortening without redirection. Put in a godawful long Amazon link and get back a shorter Amazon link. Works with eBay and a few others too. I welcome recipes for other sites. (For the programmers in the audience, which is most of you -- yes, the processing is via regular expressions.) It does some basic checks to confirm that the shortened URL returns the same page as the original one. Link expansion. Put in a link from a URL shortening/redirection service, e.g. bit.ly, and see where it redirects to. Works with a slew of popular link-shorteners, including the house brands goo.gl and nyti.ms. Some of the shortening services do offer a way to see the link target before you visit it, but they're all different; this presents a simple unified interface to that feature. There's a bookmarklet too. If you have someone in your online life who frequently bombards you with, say, mile-long eBay links, tell them about it. http://urlworks.appspot.com/ -
Simple full text search
The full text search has now been implemented. ScratchBlog can now perform powerful full-text search on the current blog posts. This full-text search has been implemented using an entirely new search module written from scratch, which uses simple python, combined with the power of python regular expressions. This new module can be used with other Django projects, as well as with django-nonrel projects along with GAE, if required. It doesn't intend to replace any existing text-search engines which are intended for any sort of complex or scalable searches, where huge amount of data is directly involved. You may use this for simple full-text search on the fly, without using any sort of indexing. It is ideal for any small projects, or where the data volume for the text don't go blizzard. This search module will be released here soon. Till then, keep searching. -
Simple full text search
The full text search has now been implemented. ScratchBlog can now perform powerful full-text search on the current blog posts. This full-text search has been implemented using an entirely new search module written from scratch, which uses simple python, combined with the power of python regular expressions. This new module can be used with other Django projects, as well as with django-nonrel projects along with GAE, if required. It doesn't intend to replace any existing text-search engines which are intended for any sort of complex or scalable searches, where huge amount of data is directly involved. You may use this for simple full-text search on the fly, without using any sort of indexing. It is ideal for any small projects, or where the data volume for the text don't go blizzard. This search module will be released here soon. Till then, keep searching. -
Announcing Django Packages!
I'm part of a two person team that just launched that BETA site for http://djangopackages.com, a site that is designed to list all the Django Applications, Frameworks, and Packages created by the Django community. While there are already a few places to look for these things, it is quite easy to argue that they are challenging to navigate, don't give any hard metrics, or are woefully incomplete/unstable/closed. Our goal was to provide an attractive, easy-to-navigate, easy-to-add-data, stable site and share it with the world.Also, this was our entry into Django Dash 2010, and was the culmination of a few days of brainstorming over paper, a lot of research, and two days of feverish coding/designing. The project was feature complete to our specifications at 5pm the second day, and the rest of the time was spent adding in UI tweaks, usability enhancements, and trying to deploy our creation.Since then, we've cleaned up a the UI, improved the design, and got the site stable. The code is open source and on github, so fork and contribute!Design Consideration: No 'Like' button or 'Rate my app' rating systemsWe wanted hard metrics. So the package numbers are pulled from the repo sites such as Github, … -
Django Dash Lessons Learned
Our experience with Django Dash 2010 was that it was an wonderful exercise in classic Django development, cowboy/cowgirl coding, and drinking copious amounts of caffeinated beverages. The result, Django Packages, is something we are happy with, are continuing to improve, and hope will improve the community.Lesson: Fixtures are a mustDjango gives you this amazing Admin control panel. As soon as you get your models in place and are entering test data, start creating fixtures. For the dash we named them initial_data.json and loaded them into the individual app directories. This meant that every time we blew away the database we got a reload with records in place. Sometimes this means you have to hand-edit JSON (or YAML if you swing that way), but the alternative is to waste time re-entering the same data again and again. Don't forget to change the names of your test fixtures before you launch!From the command-line how to save a fixture pydanny-style:./manage.py dumpdata package > apps/packages/fixtures/initial_data.jsonOne nice thing about fixtures is that when you do have the time/need, you can use them to help you write tests. And it makes development easier for contributors.Lesson: Research ahead of timeIn the days before the contest, we researched to see … -
New features for Django Packages
-
Quina calor!
Aquestes darreres setmanes han estat d'allò més interessants, caloroses però interessants. La calor ha vingut fonamentalment d'uns dies que hem passat a Menorca. Ja hi havia anat una vegada de vacances i me va encantar, aquesta vegada no ha estat diferent, encara que hi havia molta més gent que la darrera vegada. Però no vull donar enveja, així que també toca parlar de programació. Aquests dies hem estat i encara estarem durant unes quantes setmanes més, fent feina amb un projecte que implica fer feina amb un cms anomenat ezPublish. L'ezPublish és un CMS prou potent, orientat a treure continguts sigui com sigui. Tu escrius el que sigui a la part de l'administrador i l'eZ intentarà renderitzar-ho com pugui. Supòs que si el que importa és el contingut en sí això és fantàstic, però quan es tracta d'afegir-hi regles de negoci per damunt eZPublish és un malson comparat amb frameworks com Django. Està clar que no podem fer una comparació justa ja que ezPublish no té la flexibilitat d'un framework però crec que l'experiència serveix per reafirmar-me amb l'apreciació de que si el teu negoci no és generar continguts sinó que vols controlar el que passa a la web i … -
Musings about django.contrib.auth.models.User
Dawned on me that the Django auth user model that ships with Django is like the string built-in of a high level programming language. With the string built-in it's oh so tempting to add custom functionality to it like a fancy captialization method or some other function that automatically strips whitespace or what not. Yes, I'm looking at you Prototype for example. By NOT doing that, and leaving it as it is, you automatically manage to Keep It Simple Stupid and your application code makes sense to the next developer who joins your project. I'm not a smart programmer but I'm a smart developer in that I'm good at keeping things pure and simple. It means I can't show off any fancy generators, monads or metaclasses but it does mean that fellow coders who follow my steps can more quickly hit the ground running. My colleagues and I now have more than ten Django projects that rely on, without overriding, the django.contrib.auth.models.User class and there has been many times where I've been tempted to use it as a base class or something instead but in retrospect I'm wholeheartedly happy I didn't. The benefit isn't technical; it's a matter of teamwork …