Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
CouchDB with Python
Today I’ve been investigating CouchDB a little better (only heard some rumors about it before). It’s actually a pretty nice technology which can, in some places, be pretty useful… I tend to compare it to caching serialized PHP associative arrays or Python dict’s in a Memcached server using some specific prefixes, except it’s not really memory-based (it’s persistent), you get a complete query interface (views), there’s dataset versioning support (!), etc. While writing this I start to wonder what similarities I ever saw between CouchDB and a Python pickled dict in Memcached… Anyway, one use case I saw was site user profiles: profile data is most of the time not relational at all, so why store it in a relational database, which makes it sometimes rather hard to add extra profile information fields, unless you use some dirty ‘save serialized form’ trick, which renders your data unqueryable? Storing profile information (using eg. a user’s primary email address or login name as key for the user profile document) in CouchDB allows you to extend the profile “schema” easily: just add a field to your profile editting form, make sure it’s processed server-side an stored in the profile document, and add some … -
Django domain redirect middleware
Most web developers know it’s possible to serve one site on several domains or subdomains, using eg. the ServerAlias Apache directive. Sometimes this behaviour is not wanted: you want your main domain to be “foo.tld”, although “www.foo.tld” should work too, and maybe even some completely different domains. This way it’s possible to have permalinks, and you won’t get bad points from search engine spiders who don’t like the same content to be available on several URIs. In Django there’s the PREPEND_WWW setting, which will force all requests to be redirected to www.foo.bar when coming in on foo.bar, etc. This functionality is rather limited though. As I wanted to be able to have one unique main domain in my new application, I wrote a middleware which accomplishes this in a very generic way, using the django.contrib.sites framework. You need to add this middleware before all others in your settings file, even before the CommonMiddleware. Here’s the code: from django.contrib.sites.models import Site from django.http import HttpResponsePermanentRedirect from django.core.urlresolvers import resolve from django.core import urlresolvers from django.utils.http import urlquote class DomainRedirectMiddleware(object): def process_request(self, request): host = request.get_host() site = Site.objects.get_current() if host == site.domain: return None # Only redirect if the request is … -
Two Django snippets
Last 2-3 days I’ve been working on this new site project. As (almost) all web projects I started last 2 years, I’m using the Django framework to develop the site, as I just love it for several reasons. Tonight I’d like to share 2 snippets. The first one is one I use quite regularly. It’s a replacement for django.shortcuts.render_to_response, which requires one to always add a RequestContent keyword argument to be able to access MEDIA_URL etc in templates. This replacement (which I mostly put in utils/shortcuts.py) is completely API-compatible with the default render_to_response implementation, but if you pass it a request object as first parameter (and no context_instance), it automaticly uses a RequestContext. from django.shortcuts import render_to_response as real_render_to_response from django.http import HttpRequest from django.template.context import RequestContext def render_to_response(*args, **kwargs): # Check old API if len(args) > 0 and not isinstance(args[0], HttpRequest): return real_render_to_response(*args, **kwargs) if not kwargs.get('context_instance', None): kwargs['context_instance'] = RequestContext(args[0]) return real_render_to_response(*args[1:], **kwargs) The second one is an custom form which can be used with the django-contact-form application. It automaticly uses the name and email address of the user if logged in, otherwise provides the standard text input fields. It might be a good example of how to … -
Using Django’s FormPreview with @login_required
As part of Django’s ‘batteries included’ philosophy, it comes with the FormPreview class to make it easy to automate this workflow: “Display an HTML form, force a preview, then do something with the submission.” Also provided is the @login_required decorator which makes it easy and obvious to mark functions as requiring a logged-in user. Both [...] -
Picture gallery using MooTools
After dealing with Windows Vista some time ago there was this idea about creating an image gallery for the web that looks like the tab view in vista using the aero user interface. First you could think about creating this with flash but it's also possible with javascript and the mootools framework. It took a long time until it worked properly for putting it into the web, mainly because there was rarely time working on it. I created an extra page for the script that answers to the name of "ImageFlip" because I'll continue working on it. If you have any questions, ask me here or write an email as specified on the page: to the ImageFlip minpage.... -
Picture gallery using MooTools
After dealing with Windows Vista some time ago there was this idea about creating an image gallery for the web that looks like the tab view in vista using the aero user interface. First you could think about creating this with flash but it's also possible with javascript and the mootools framework. It took a long time until it worked properly for putting it into the web, mainly because there was rarely time working on it. I created an extra page for the script that answers to the name of "ImageFlip" because I'll continue working on it. If you have any questions, ask me here or write an email as specified on the page: to the ImageFlip minpage.... -
Picture gallery using MooTools
After dealing with Windows Vista some time ago there was this idea about creating an image gallery for the web that looks like the tab view in vista using the aero user interface. First you could think about creating this with flash but it's also possible with javascript and the mootools framework. It took a long time until it worked properly for putting it into the web, mainly because there was rarely time working on it. I created an extra page for the script that answers to the name of "ImageFlip" because I'll continue working on it. If you have any questions, ask me here or write an email as specified on the page: to the ImageFlip minpage.... -
2008 Digital Edge Award Finalists
The 2008 DIgital Edge Award finalists were just announced, and I’m excited to see several World Company sites and projects on there as well as a couple of sites running Ellington and even the absolutely awesome Django-powered PolitiFact.com. At work we don’t do what we do for awards. We do it to serve our readers, tell a story, get information out there, and do it as best we can. At the same time even being nominated as finalists is quite an honor, and evokes warm fuzzy feelings in this programmer. Here are the various World Company projects and sites that were nominated (in the less than 75,000 circulation category): Most Innovative Multimedia Storytelling: 24 Hours in Lawrence (LJWorld.com) Best Local Guide or Entertainment Site: Lawrence.com Best Design and Site Architecture: LJWorld.com Best Overall News Site: LJWorld.com Not too shabby for a little media company in Kansas. I’m particularly excited about the LJWorld.com nominations since it hasn’t been too long since we re-designed and re-launched the site with a lot of new functionality. Scanning the finalists I also see a couple of other sites running Ellington as well as several special projects by those sites. As someone who writes software for … -
Django Template Tag for Dictionary Access
About a million times when writing Django pages I’ve been iterating through a list of objects and wanted to look up a value in a dictionary keyed by object.id. But you can’t, the built-in tags don’t allow it. The standard workaround is to loop over the list and zip the hash data into some kind [...] -
Django internationalisation
Multilingual web site with djangoI have been recently working on a web application that needs to support several languages, English and French among others. This web application is built on top of Django which has a nice built in support for internationalisation, also known as i18n. However along the road of building this web application I have noticed some gaps between what was existing and what I was trying to achieve.Here it is the list whithout any particular order:- a multilingual flatpages- a way to explicitely use display the language code (ie fr for French and en for English) directly in the URL. I do prefer http://yml.alwaysdata.net/fr/help instead of http://yml.alwaysdata.net/ and rely on the browser settings to direct my user the right page. In addition I have the feeling that this would result in a much better indexation by search engine like Google or Yahoo, ...- a simple UI to set the language.The good news is that after some time, search and chat on IRC I have found a way to close all of them.Multilingual flatpagesThis has been amazingly simple thanks to django-multilingual, a library kindly developped by ???. In a matter of one or two hours I have forked … -
Rolling your own simple authentication system for Django
Sometimes you need to roll a simple authentication system for Django. For example, I just hacked a client interface on our corporate intranet at GMTA, using a similar approach as the one I will describe here. The solutions consists of four parts: Extending the model to include a password Login form Login / Logout views A login_required decorator for views to require authentication Extending the model In order for us to authenticate a Client we need to add a password to the model. As it is not good practice to store passwords in plain text in the database, we will store the password as a salted hash. In this example I will use the SHA-1 secure hash function. We will add two functions to the Client model in order to handle the hashing itself. This is also helpful if we later in the project decides to change the hashing algorithm used. The two functions and the password field: password = models.CharField(maxlength=40) def update_password(self, new_password): self.password = sha.new(settings.PASSWORD_SALT + new_password).hexdigest() def check_password(self, password): hsh = sha.new(settings.PASSWORD_SALT + password).hexdigest() return hsh == self.password In order to update the password for a Client we just call the update_password method - as well as … -
Rolling your own simple authentication system for Django
Sometimes you need to roll a simple authentication system for Django. For example, I just hacked a client interface on our corporate intranet at GMTA, using a similar approach as the one I will describe here. The solutions consists of four parts: Extending the model to include a password Login form Login / Logout views A login_required decorator for views to require authentication Extending the model In order for us to authenticate a Client we need to add a password to the model. As it is not good practice to store passwords in plain text in the database, we will store the password as a salted hash. In this example I will use the SHA-1 secure hash function. We will add two functions to the Client model in order to handle the hashing itself. This is also helpful if we later in the project decides to change the hashing algorithm used. The two functions and the password field: password = models.CharField(maxlength=40) def update_password(self, new_password): self.password = sha.new(settings.PASSWORD_SALT + new_password).hexdigest() def check_password(self, password): hsh = sha.new(settings.PASSWORD_SALT + password).hexdigest() return hsh == self.password In order to update the password for a Client we just call the update_password method - as well as … -
Django Menuing System
On most of the websites that I've built with Django, I have had a desire to be able to manage little elements of the website from the Django administration screen without having to touch my templates. My intent is for the templates to become the presentation vehicle, with anything that matters being built out of the Django databases. One such thing that I want to keep out of my templates is navigation. Sure, the template has a place for navigation (including an empty ), but the contents of my navigation bars are driven by a dynamic Django application. The application has but two files: the models and a template tag. First up is the model file, menu/models.py: from django.db import models class Menu(models.Model): name = models.CharField(maxlength=100) slug = models.SlugField() base_url = models.CharField(maxlength=100, blank=True, null=True) description = models.TextField(blank=True, null=True) class Admin: pass def __unicode__(self): return "%s" % self.name def save(self): """ Re-order all items at from 10 upwards, at intervals of 10. This makes it easy to insert new items in the middle of existing items without having to manually shuffle them all around. """ super(Menu, self).save() current = 10 for item in MenuItem.objects.filter(menu=self).order_by('order'): item.order = current item.save() current += 10 … -
Django Menuing System
On most of the websites that I've built with Django, I have had a desire to be able to manage little elements of the website from the Django administration screen without having to touch my templates. My intent is for the templates to become the presentation vehicle, with anything that … -
Django Brasil no ar!
Após grande expectativa, está no ar o site da comunidade Django Brasil (http://www.djangobrasil.org/)! O objetivo é ser um veículo de divulgação deste framework em terras tupiniquins, trazendo informações para auxiliar tanto os iniciantes quanto os mais experientes.Atualmente o site fornece: as principais características do Django; um weblog para anúncios e avisos à comunidades brasileira; uma página exclusiva para a comunidade descrevendo como um desenvolvedor pode participar; um agregador de blogs (planeta) dos desevolvedores nacionais, e; uma área específica para a documentação. A documentação e tradução da documentação oficial ainda é escassa. Convidamos os interessados em traduzir ou produzir conteúdo em língua portuguesa para suprir essa necessidade.Este é apenas o início de uma nova fase da comunidade Django Brasil. Participe!O site foi desenvolvido pelo Guilherme Mesquita Gondim (semente) e o belo desing pelo Jader Rubini (http://jaderubini.wordpress.com). O código é livre e pode ser acessado no seguinte endereço: http://code.google.com/p/djangobrasil/. -
Django Brasil no ar!
Após grande expectativa, está no ar o site da comunidade Django Brasil! O objetivo é ser um veículo de divulgação deste framework em terras tupiniquins, trazendo informações para auxiliar tanto os iniciantes quanto os mais experientes.Atualmente o site fornece: as principais características do Django; um weblog para anúncios e avisos à comunidades brasileira; uma página exclusiva para a comunidade descrevendo como um desenvolvedor pode participar; um agregador de blogs (planeta) dos desevolvedores nacionais, e; uma área específica para a documentação. A documentação e tradução da documentação oficial ainda é escassa. Convidamos os interessados em traduzir ou produzir conteúdo em língua portuguesa para suprir essa necessidade.Este é apenas o início de uma nova fase da comunidade Django Brasil. Participe!O site foi desenvolvido pelo Guilherme Mesquita Gondim (semente) e o belo desing pelo Jader Rubini (http://jaderubini.wordpress.com). O código é livre e pode ser acessado no seguinte endereço: http://code.google.com/p/djangobrasil/. -
Usando o ZODB no Django
Ter a flexibilidade da orientação a objetos do Python em um banco de dados pode ser algo muito útil e interessante que utilizar bancos relacionais. Um dos melhores bancos orientado a objetos em Python é o ZODB , é poderoso e simples de utilizar.Mas como utilizar ele para web?A resposta mais óbvia é Zope e Grok . São dois frameworks para web que utilizam ZODB como base de dados!A resposta não tão óbvia é o Pylons . O Pylons é um framework que trabalha através de camadas (middlwares) onde você uma dessas camadas pode ser a implementação para suporte a ZODB.E a resposta nada óbvia é o Django. O Django é um framework famoso pela sua coesão, mas isso não quer dizer que ele não pode ser facilmente integrado com outras ferramentas. Uma das provas disso é o tranquil, uma middlware que integra o Django ao SQLAlchemy .Inspirado pela necessidade de usar o ZODB , por não querer usar Grok , Pylons ou outro e pela implementação do tranquil, implementei o django-zodb, uma middlware que integra o Django ao ZODB.O endereço do projeto é: http://code.google.com/p/django-zodb/Para instalar o projeto basta ler a página do wiki do projeto: http://code.google.com/p/django-zodb/wiki/InstallationNo projeto tem um … -
Case-insensitive ordering with Django and PostgreSQL
When the Django Gigs site first went live we noticed the ordering of developers by name was not right. Those starting with an uppercase letter were coming before those starting with a lowercase letter. PostgreSQL and the locale PostgreSQL has a locale setting which is configured when the cluster is created. Among other things, this affects the ordering of results when you use the SQL order by clause. The local on my server was set to “C” which means it uses byte-level comparisons, rather than following more complex rules for a given culture. Although this is apparently good for performance, it means order by will be case sensitive – e.g. “Zebra” comes before “apple”. Depending on how your system is set up, you may have locales such as en_GB. The locale can’t easily be changed in PostgreSQL because indexes and other data depends on it. To change locale, you need to start a new cluster and move databases to it. Django and case-sensitivity Django provides the order_by() function on QuerySets, but does not have an option for case insensitive ordering. Instead this is left to your database configuration. When using SQL directly, you can sort case-insensitively using the PostgreSQL lower() … -
WebService with PHP Server and Java Client
For my current private project that answers to the nice name "Telrunya" I'm trying to access a PHP web service through a Java client. I once heard in a .NET codecamp that WebServices are super cool and that it doesn't matter in which language they are implemented. But that doesn't apply if you're communication between 2 different technologies. In the Guxx blog I found the reversed case, how to access a java server through a PHP client. There is also a Java bridge developed by Zend that manages the conversion of the objects. But that seems to be an independent server or at least a server modul but that isn't considered by me. (furthermore it costs money) Anyway, I tried the whole thing withion NetBeans IDE with JAX-WS. My WSDL file (document) written in Eclipse was successfully parsed and the Java files for client etc. were created. The client was also able to access the service but it failed to convert the values. Monitoring the HTTP traffic I can see that the right values are returned, but the Java client returns "null". I already read a lot of documentations and tutorials but I didn't find out anything about converting the … -
WebService with PHP Server and Java Client
For my current private project that answers to the nice name "Telrunya" I'm trying to access a PHP web service through a Java client. I once heard in a .NET codecamp that WebServices are super cool and that it doesn't matter in which language they are implemented. But that doesn't apply if you're communication between 2 different technologies. In the Guxx blog I found the reversed case, how to access a java server through a PHP client. There is also a Java bridge developed by Zend that manages the conversion of the objects. But that seems to be an independent server or at least a server modul but that isn't considered by me. (furthermore it costs money) Anyway, I tried the whole thing withion NetBeans IDE with JAX-WS. My WSDL file (document) written in Eclipse was successfully parsed and the Java files for client etc. were created. The client was also able to access the service but it failed to convert the values. Monitoring the HTTP traffic I can see that the right values are returned, but the Java client returns "null". I already read a lot of documentations and tutorials but I didn't find out anything about converting the … -
WebService with PHP Server and Java Client
For my current private project that answers to the nice name "Telrunya" I'm trying to access a PHP web service through a Java client. I once heard in a .NET codecamp that WebServices are super cool and that it doesn't matter in which language they are implemented. But that doesn't apply if you're communication between 2 different technologies. In the Guxx blog I found the reversed case, how to access a java server through a PHP client. There is also a Java bridge developed by Zend that manages the conversion of the objects. But that seems to be an independent server or at least a server modul but that isn't considered by me. (furthermore it costs money) Anyway, I tried the whole thing withion NetBeans IDE with JAX-WS. My WSDL file (document) written in Eclipse was successfully parsed and the Java files for client etc. were created. The client was also able to access the service but it failed to convert the values. Monitoring the HTTP traffic I can see that the right values are returned, but the Java client returns "null". I already read a lot of documentations and tutorials but I didn't find out anything about converting the … -
Stockphoto 0.2.1 released
I've just released stockphoto 0.2.1. This is a bugfix release and contains no new features relative to 0.2. I would ... -
Stockphoto 0.2.1 released
I've just released stockphoto 0.2.1. This is a bugfix release and contains no new features relative to 0.2. I would like to thank many people for bug reports on the previous version; plese see the credits in the README file. I'll be opening development on stockphoto 0.3 once I decide the best way to host a public version control repository (Google code vs. Savannah, vs self-hosting). The pre-0.3 branch will include new features, some of which are listed as to-dos in the current README. -
Django Book Update
A quick update on the Django Book: Adrian and I wrapped up the last few bits last week, and the book went to the printer on Friday. It should start shipping to bookstores around the second week of December. There’s still a fair amount of work that needs to be done on the website, so I can’t put the final version of the book up just yet. However, the final book will be available online around the same time as the dead tree version. -
Segundo Django Sprint dia 1 de Dezembro
Sprint é um evento onde os desenvolvedores, colaboradores e simpatizantes com alguma ferramenta opensource se unem para implementar novidades de arrumar erros existentes nessa ferramenta. E dia 1 de Dezembro ocorrerá o segundo Django Sprint desse ano. Para participar do Sprint, inscreva-se na página do wiki do Django e no dia do Sprint fique atento no canal #django-sprint, onde todos os envolvidos com o Sprint e os responsáveis pelo código do Django estarão para auxiliar e tirar dúvidas. Se você ainda não conhece o processo de criação de tickets, envio de path's utilizado no desenvolvimento do Django, leia esse artigo: Contributing to Django.