I will talk about a shortcut I developed for the Django framework and always use in my apps. This code is aimed in making a quik shortcut to obtain the first object of a queryset if it exists or None otherwise.
It’s very useful when you want to display the last news in the first page of your website, but don’t want it to break if there isn’t one to show. It’s just a use case for such a code, but there are many more.
In the past I used to write something like this:
try:
first_user = User.objects.all()[:1][0]
except IndexError:
first_user = None
This is four lines to do a very simple task and I wanted to evolve this to use only one line of code. So I developed a function that do this to me. It’s inspired in the django.shortcuts.get_object_or_404. Let’s take a look at the code:
def get_first_object_or_none(queryset):
try:
return queryset[:1][0]
except IndexError:
return None
I’ve put this code in a module called shortcuts inside my project and now everytime I want to use it I can write this code:
from shortcuts import get_first_object_or_none
first_user = get_first_object_or_none(User.objects.all())
I think it’s a very good result and helps a lot in my coding. It also made my code more legible and easy to understand. It increased my productivity and I am publishing to increase others productivity also. Any doubts, questions os suggestions, please leave a comment.
Tags: Django, orm, Python, queryset
MXHR stands for multiple XmlHttpRequests and was created some days ago by digg.com front end engineers.
This awesome technology lets front end engineers request more than one resource in a single XmlHttpRequest.
As an example you will be able, in the future (the project is in alpha release), to get a javascript file, a css and some images with only one request, meaning that you will consume less bandwidth, will get data faster and it will be ordered the way you want. Cool huh?
See more detais on digg’s blog.
The aggregation is already available in Django SVN version. Now, it’s possible to do things such count authors of all book entries, count comments os all post entries, sum values of all sales to a client and much more.
Here is the official documentation of this feature: http://docs.djangoproject.com/en/dev/topics/db/aggregation/
Tags: aggregation, Django, orm
A good feature of Django Framework is the template tags and template filters. But it sucks when you have to load the filters in each template like this:
{% load mytemplatetags %}
It was much better if you just use the filters, without the need to load it. The reason you have to load is to achieve a better performance. But there’s a function of the template module called add_to_builtins that solves this problem. You can easily define a template tag or filter as builtin and use it like the builtin django template tags and filters. Just put this code in a file that is loaded ever, like the init.py of your project.
from django.template import add_to_builtins
add_to_builtins('path.to.templatetags.file')
Where ‘path.to.templatetags.file’ is the path of the file containing the template tags. For example, I have an app, inside my project, named mytagsapp. Inside this app I have the module templatetags with a file named mytags.py with my custom tags. So I will have to call add_builtins(‘mytagsapp.templatetags.mytags’). My project folder should look like this:

Folders structure
Make sure your app is in the INSTALED_APPS setting in your settings.py project. It will guarantee that the init.py of you app will get called. So just put the code above in this file (red in image).
Remember to not use this feature with all your template filters as it will mean loss of performance.
Tags: builtins, Django, Python, template filters, template tags
When you use a Model Choice Field in Django, it automatically creates an empty option in the generated select widget. But in some special cases, you don’t want this empty option to be there. So I decided to find the way to remove it. It’s much more simple then you think. Just create your model declaring the model choice field like this:
fieldname = forms.ModelChoiceField(queryset=RelationModel.objects,empty_label=None)
It’s simple like that. Just set the empty_label argument to None. But whe using ModelFormSets, there is a little more work to do. You have to create a new BaseModelFormSet like this:
from django.forms.models import BaseModelFormSet</p>
<p>class MyBaseModelFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(MyBaseModelFormSet,self).add_fields(form,index)
form.fields['fieldname'] = forms.ModelChoiceField(queryset=RelationModel.objects,empty_label=None)
Pay atention that you have to override the add_fields method and change your field in the form fields array. Finally you have to pass this BaseModelFormSet as argument to the modelformset_factory:
from django.forms.models import modelformset_factory</p>
<p>MyModelFormset = modelformset_factory(MyModel,formset=MyBaseModelFormSet)
Tags: Django, formset, Python