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
No dia 24 de abril de 2009, no SENAC em Natal/RN, ocorreu o FLISOL. Neste evento, eu ministrei um mini curso de django. Então estou disponibilizando tanto os arquivos_mini_curso desenvolvido durante o curso, como os slides.
Tags: Django, flisol, mini-curso

Venho através deste convidá-los ao FLISOL/RN 2009. O Festival Latino-americano de Instalação de Software Livre do RN irá acontecer no dia 25 de abril de 2009 no SENAC em Natal.
No evento eu irei ministrar um mini-curso introdutório ao framework Django das 14:00 as 17:00 horas, cujo objetivo é formar pessoas com conhecimentos básicos acerca do framework. O mini-curso irá abordar diversos conceitos do django através do desenvolvimento de um blog.
Maiores informações sobre o evento podem ser encontradas no site.
Tags: Django, flisol, minicurso
Sphinx is a great documentation tool, and one of it’s built-in extensions is sphinx.ext.intersphinx. It simply takes your objects references for other projects and converts to links in the other project’s documentation.
In sphinx-quickstart command, it asks if you want to add this extension. If so, It adds this code to your conf.py file:
extensions = ['sphinx.ext.intersphinx']
intersphinx_mapping = {'http://docs.python.org/dev': None}
As you can see, it comes integrated with python documentation by default. But what I want is to integrate with Django documentation. So I changed the code a little bit:
extensions = ['sphinx.ext.intersphinx']
intersphinx_mapping = {
'http://docs.python.org/dev': None,
'http://docs.djangoproject.com/en/dev': 'http://docs.djangoproject.com/en/dev/_objects',
}
Sphinx looks for default for the file name objects.inv inside the documentation root, but django doesn’t provide such a file. Since ticket #10315 they provided a file like objects.inv but with a different URL: http://docs.djangoproject.com/en/dev/_objects/.
Now, all you have to do is reffer to classe or any kind of objects inside django: :class:django.contrib.auth.models.User. It will refference the User documentation inside django’s docs.
Tags: Django, docs, documentation, Python, sphinx
I decided to document my Django projects with the same tool used by Django team: Sphinx. It is a very good documenting tool, and was used for many other projects, including the Python Project itself.
But it has a simple problem with Django, that I found the solution rlazo’s blog. But it still has some problems, when you are trying to document a pluggable app, that doesn’t have a project, you have to configure the django settings without the project settings, since pluggable apps doesn’t have a settings module.
Thanks to apollo13, who shown me this better approach, you can simply add this code to sphinx’s conf.py file:
from django.conf import settings
settings.configure()
With this approach, you don’t need to add any kind of fake files in your project.
Tags: Django, docs, documentation, pluggable apps, sphinx
It’s easy to create a custom template for HTTP 500 errors. All you have to do is create a file named 500.html in any of the application’s TEMPLATE_DIRS. But in almost all cases you want to use media in this page. It’s good to have an error page with the same look and feel of the system itself.
The default HTTP 500 handler in django uses Context instead of RequestContext. It means that none of your template context processors will be loaded, and the MEDIA_URL variable available in the template system comes exactly from one of these processors. So, without template context processors, we get no MEDIA_URL variable in templates.
Searching in google for a solution to this problem I found a snippet[1] that solves the MEDIA_URL problem. But it still doesn’t load the processors, all it does is pass the MEDIA_URL variable to the context for template. So I decided to make simple changes in it to load the processors. And here is the complete code:
def server_error(request, template_name='500.html'):
from django.template import RequestContext
from django.http import HttpResponseServerError
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
Put this code in any views file you want and then define it as the handler500 in your urls.py:
handler500 = 'views.server_error'
[1] http://www.djangosnippets.org/snippets/1199/
Tags: context, Django, media_url, template context processor