Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Multiple cache backends in Django
Out of the box, Django’s cache framework includes different cache back-ends (including the venerable memcached) and granularities (site-wide, view-specific, etc.). How could you improve on this awesomeness? One way is to use multiple back-ends. This might be desirable if your application needs a vanilla-flavored memcache for the site, and a second cache for a data [...] -
Afficher la version de django
un petit mémo tout con, mais qui peut-être utile. Il peut arriver d'avoir besoin d'afficher la version de django utilisé pour un projet précis. Comment faire ? La fonction get_version() du __init__ de django est la pour ça. Un petit from django import get_version est le tour est donc joué. -
Django and AJAX image uploads
Note: this is a repost from my blog. You can find the original post here. This is my first post to the Mozilla WebDev blog. Woot, exciting! Table of contents: Demo Summary Server side (Django) Model Form View Generating the thumbnail with PIL Client side Graceful degradation Demo Screencast Screenshots: The upload form, empty and [...] -
Django and AJAX image uploads
Note: this is a repost from my blog. You can find the original post here. This is my first post to the Mozilla WebDev blog. Woot, exciting! Table of contents: Demo Summary Server side (Django) Model Form View Generating the thumbnail with PIL Client side Graceful degradation Demo Screencast Screenshots: The upload form, empty and [...] -
Going Green
There are so many ways to serve up Django and other WSGI apps. I’ve used nginx and uWSGI (thanks to a great blog post by Zachary Voase), IIS and isapi-wsgi, Apache and mod_wsgi, and even CherryPy as a development “runserver” replacement. I’ve recently started hearing more and more about asynchronous servers, lightweight threads, and greenlets and such. I also came across the Green Unicorn project that, though not very speedy with its default worker class, has recently integrated gevent to make it a very attractive offering. This post describes how I got a Django project up and running on WebFaction (affiliate link) using Gunicorn and gevent. It was quite fun! One of the advantages of using this method on WebFaction in particular is that they already have nginx running in front of all your apps. It bothered me, when using uWSGI, that I had to have an additional nginx instance running, or having to run full blown Apache to use mod_wsgi. Simpler is better and, even though I opted to compile some things, Gunicorn seemed simpler. Especially when it came to finally running the Django project. Install Python As you’ll see with most of this, I like to play with … -
Google Analytics referring sites and https
The problem: recently a client reported the he does not see another site he owns in the list of referring sites in his Google Analytics account(for his main website) but was absolutely sure that he recieves trafic from this website. The research and the reason: at first I thought that the problem is cause by [...] -
Going Green
There are so many ways to serve up Django and other WSGI apps. I’ve used nginx and uWSGI (thanks to a great blog post by Zachary Voase), IIS and isapi-wsgi, Apache and mod_wsgi, and even CherryPy as a development “runserver” replacement. I’ve recently started hearing more and more about asynchronous servers, lightweight threads, and greenlets and such. I also came across the Green Unicorn project that, though not very speedy with its default worker class, has recently integrated gevent to make it a very attractive offering. This post describes how I got a Django project up and running on WebFaction (affiliate link) using Gunicorn and gevent. It was quite fun! One of the advantages of using this method on WebFaction in particular is that they already have nginx running in front of all your apps. It bothered me, when using uWSGI, that I had to have an additional nginx instance running, or having to run full blown Apache to use mod_wsgi. Simpler is better and, even though I opted to compile some things, Gunicorn seemed simpler. Especially when it came to finally running the Django project. Install Python As you’ll see with most of this, I like to play with … -
Django Patterns: Pluggable Backends
As the first installment in a series on common patterns in Django development, I'd like to discuss the Pluggable Backend pattern. The pattern addresses the common problem of providing extensible support for multiple implementations of a lower level function, be it caching, database querying, etc. -
Django Patterns: Pluggable Backends
As the first installment in a series on common patterns in Django development, I'd like to discuss the Pluggable Backend pattern. The pattern addresses the common problem of providing extensible support for multiple implementations of a lower-level function, for example caching, database querying, etc. Problem The use of this pattern often coincides with places where the application needs to be configurable to use one of many possible solutions, as in the case of database engine support. Consider the following: The application needs to support Backend A and Backend B but if you look closely at the methods exposed there are some discrepancies: Backend A has slightly more verbose method names than Backend B Backend B does not accept a default value on the get() method In Django we see this pattern all over the place: django.contrib.auth django.contrib.messages django.contrib.sessions django.core.cache django.core.files.storage django.core.mail django.core.serializers django.db Analysis Here is a first stab at getting our Application to talk to backend A and B: class ApplicationBackend(object): def __init__(self, backend): # here we are self.backend = backend def get(self, key, default=None): if isinstance(self.backend, BackendA): return self.backend.get_data(key, default) elif isinstance(self.backend, BackendB): try: return self.backend.get(key) except BackendB.KeyError: return default def set(self, key, value): ... etc ... Notice … -
Django Patterns: Pluggable Backends
As the first installment in a series on common patterns in Django development, I'd like to discuss the Pluggable Backend pattern. The pattern addresses the common problem of providing extensible support for multiple implementations of a lower-level function, for example caching, database querying, etc. Problem The use of this pattern often coincides with places where the application needs to be configurable to use one of many possible solutions, as in the case of database engine support. Consider the following: The application needs to support Backend A and Backend B but if you look closely at the methods exposed there are some discrepancies: Backend A has slightly more verbose method names than Backend B Backend B does not accept a default value on the get() method In Django we see this pattern all over the place: django.contrib.auth django.contrib.messages django.contrib.sessions django.core.cache django.core.files.storage django.core.mail django.core.serializers django.db Analysis Here is a first stab at getting our Application to talk to backend A and B: class ApplicationBackend(object): def __init__(self, backend): # here we are self.backend = backend def get(self, key, default=None): if isinstance(self.backend, BackendA): return self.backend.get_data(key, default) elif isinstance(self.backend, BackendB): try: return self.backend.get(key) except BackendB.KeyError: return default def set(self, key, value): ... etc ... Notice … -
Django Patterns: Pluggable Backends
As the first installment in a series on common patterns in Django development, I'd like to discuss the Pluggable Backend pattern. The pattern addresses the common problem of providing extensible support for multiple implementations of a lower-level function, for example caching, database querying, etc. Problem The use of this pattern often coincides with places where the application needs to be configurable to use one of many possible solutions, as in the case of database engine support. Consider the following: The application needs to support Backend A and Backend B but if you look closely at the methods exposed there are some discrepancies: Backend A has slightly more verbose method names than Backend B Backend B does not accept a default value on the get() method In Django we see this pattern all over the place: django.contrib.auth django.contrib.messages django.contrib.sessions django.core.cache django.core.files.storage django.core.mail django.core.serializers django.db Analysis Here is a first stab at getting our Application to talk to backend A and B: class ApplicationBackend(object): def __init__(self, backend): # here we are self.backend = backend def get(self, key, default=None): if isinstance(self.backend, BackendA): return self.backend.get_data(key, default) elif isinstance(self.backend, BackendB): try: return self.backend.get(key) except BackendB.KeyError: return default def set(self, key, value): ... etc ... Notice … -
Django Patterns: Pluggable Backends
As the first installment in a series on common patterns in Django development, I'd like to discuss the Pluggable Backend pattern. The pattern addresses the common problem of providing extensible support for multiple implementations of a lower-level function, for example caching, database querying, etc. Problem The use of this pattern often coincides with places where the application needs to be configurable to use one of many possible solutions, as in the case of database engine support. Consider the following: The application needs to support Backend A and Backend B but if you look closely at the methods exposed there are some discrepancies: Backend A has slightly more verbose method names than Backend B Backend B does not accept a default value on the get() method In Django we see this pattern all over the place: django.contrib.auth django.contrib.messages django.contrib.sessions django.core.cache django.core.files.storage django.core.mail django.core.serializers django.db Analysis Here is a first stab at getting our Application to talk to backend A and B: class ApplicationBackend(object): def __init__(self, backend): # here we are self.backend = backend def get(self, key, default=None): if isinstance(self.backend, BackendA): return self.backend.get_data(key, default) elif isinstance(self.backend, BackendB): try: return self.backend.get(key) except BackendB.KeyError: return default def set(self, key, value): ... etc ... Notice … -
Booktools
A little-known bit of trivia about our book, Python Web Development with Django: we wrote the manuscript in Markdown. I think it was my idea. One of the major motivations for using a text-based format -- versus the unfortunate de facto standard, Microsoft Word -- was integration with good developer tools and workflow. Our manuscript and all our project code was in a Subversion repo, so each author always had the latest updates. HTML generated from the Markdown files was great for generating nice printed/printable output too. We could have used any number of similar formats: Markdown, Textile, reStructuredText. If we did it again we'd probably use reST plus Sphinx. That would grant all the same advantages, plus give us a little more formatting flexibility and tool support. This workflow enabled certain kinds of programmatic action on our text, notably two things: automated testing of the interactive examples within the text, and automated extraction of example snippets from source code files. I wrote scripts for each of these tasks. I've cleaned them up a little, to try to make them a little more general-purpose, and published them (with minimal example files) in a bitbucket repo: http://bitbucket.org/pbx/booktools There's a little documentation … -
Django on uWSGI and Nginx
I recently moved Pegasus News from Perlbal, Lighttpd, and Apache to Nginx and uWSGI. We balance the traffic between 3 physical servers, and the systems were struggling under the load even after weeks of Apache conf tweaking. We began having issues with excessively slow page loads, request timeouts, and intermittent errors with OGR transformations. I decided to move us to a lighter application server so that we could get the most out of our system resources, and after a lot of research and testing I chose uWSGI. While I was at it, I decided to replace Perlbal and Lighttpd with Nginx because of its great configuration syntax and excellent performance. I also upgraded us to Ubuntu 10.04 and Postgres 8.4. The result was a resounding success! Memory usage and CPU load on each of the web nodes dropped dramatically. Swap usage dropped to almost nothing. The overall responsiveness of the site improved noticeably, and the timeout errors and OGR failures disappeared entirely. If you'd like to give this stack a try, read on for an overview of the setup on Ubuntu 10.04. I'm using the standard Ubuntu source package for Nginx, but modifying it slightly and them installing it with … -
Django 1.2.3 lançado
Django 1.2.3 lançado -
Django 1.2.3 lançado
Django 1.2.3 lançado -
Entorns virtuals
Quan un es dedica a la programació seriosa amb Python (ja sigui amb Django o amb qualsevol altre framework) hi ha un parell de coses que s'han de tenir en compte: saber amb quina versió de Python programarem i si aquesta versió estarà suportada per la distribució del servidor de producció és una d'elles, potser la més simple. Una altra un poc més complexa és la de plantejar-nos des del principi com durem el mantenimient de l'aplicació. Amb els servidors dedicats cada cop a més bon preu, no és genys extrany plantejar-se tenir un servidor dedicat per les nostres aplicacions web en Python per exemple. És també molt habitual que les aplicacions tenguin un cicle de vida molt més llarg que les llibreries que hem utilitzat per a crear-les. Ara podem fer servir la versió 1.2.3 de Django, però d'aquí tres o quatre mesos tindrem la 1.3, amb altres llibreries pot passar una cosa semblant. Quan tenim una aplicació en producció la màxima sempre ha de ser la de si no està trencat no ho arreglis. Si la nostra aplicació funciona amb Django 1.1 i hem anat aplicant els pegats de seguretat, llavors plantejar-nos migrar a una versió major és … -
New mercurial mirror for Django stable branch 1.2
I have tried for the last few years to use one of the mercurial mirrors on bitbucket.org to follow Django. Since far before Django 1.0 was released, I was following trunk, but I have switched to the stable branch around Django 1.1. I’ve always had problems with the mirrors on bitbucket, they seem mostly unmaintained. [...] -
Python libwkhtmltox module – wrapping a C library using Cython – convert HTML to PDF
First of all, big shout out to antialize for creating wkhtmltopdf (github repo). Also, this project is being hosted on GitHub @ http://github.com/mreiferson/py-wkhtmltox. wkhtmltox What is wkhtmltox you ask? It's a utility built on Nokia's Qt framework for converting HTML (including images, CSS, and Javascript) to a PDF or image. When Qt introduced it's webkit [...] Related posts:Convert HTML to PDF in PHP (libwkhtmltox extension) Python data sharing in the multiprocessing module Django URL Parameter Passing and Python Strings -
OAuthcalypse Now: Tweeting with Twitter, OAuth and Django
The Twitter OAuthcalypse hit me last week. Back in July, I used Twitter’s basic authentication scheme in a new site I’m working on (wantbox.com) to easily send out tweets via my @wantbox account whenever someone posted a new “want” to the site. This integration took about 30 minutes to research and implement. All I had to do was put my twitter username and password in my Django project’s settings.py file, pip install the python-twitter app into my virtualenv and then use: from django.conf import settings import twitter api = twitter.Api(username=settings.TWITTER_USERNAME, password=settings.TWITTER_PASSWORD) api.PostUpdate('Someone in 02481 wants "a home gym" %s' % extra_stuff) The resulting tweet would appear in my @wantbox stream appearing to come “via API”. Easy-peasy. Last week, however, I started getting “401 Unauthorized” errors whenever I tried to post to Twitter. Clearly the Twitter API team had officially turned off basic authentication and was now requiring all apps to connect using OAuth. Yesterday around lunchtime I stopped work on the fun new wantbox feature I was working on so I could “quickly fix” my broken Twitter posting. Oh boy…quickly and OAuth clearly don’t play well together. I tried a bunch of solutions which ultimately failed. I worked through the … -
Безопасные умолчания
По наводке Романа Ворушина почитал пост Дика Липтона о том, что в проектировании систем должны закладываться безопасные умолчания. И мне вспомнилась похожая штука из истории Джанго. Когда-то давно у модели пользователя был метод is_anonymous(), который предполагалось проверять в шаблонах для определения, что показывать незалогиненному пользователю: {% if user.is_anonymous %} Login... {% else %} Hi, {{ user }} {% endif %} А потом Гэри Вилсон справедливо заметил, что это может быть не очень безопасно: если в шаблоне не будет переменной user или человек ошибётся в написании user.is_anonymous, то по умолчанию отработает та часть шаблона, которая показывается залогиненному юзеру. И с тех пор у юзера вместо is_anonymous появился обратный метод -- is_authenticated, условие поменялось на обратное, и теперь в случае ошибок шаблон не вываливает всем подряд залогиновую информацию. -
Безопасные умолчания
По наводке Романа Ворушина почитал пост Дика Липтона о том, что в проектировании систем должны закладываться безопасные умолчания. И мне вспомнилась похожая штука из истории Джанго. Когда-то давно у модели пользователя был метод is_anonymous(), который предполагалось проверять в шаблонах для определения, что показывать незалогиненному пользователю: {% if user.is_anonymous %} Login... {% else %} Hi, {{ user }} {% endif %} А потом Гэри Вилсон справедливо заметил, что это может быть не очень безопасно: если в шаблоне не будет переменной user или человек ошибётся в написании user.is_anonymous, то по умолчанию отработает та часть шаблона, которая показывается залогиненному юзеру. И с тех пор у юзера вместо is_anonymous появился обратный метод — is_authenticated, условие поменялось на обратное, и теперь в случае ошибок шаблон не вываливает всем подряд залогиновую информацию. -
Conheça o Django Packages
O Daniel Greenfeld publicou em seu blog o lançamento do Django Packages (Announcing Django Packages). O objetivo do site é listar todos os pacotes, CMS, plugins e aplicativos para deixar seus projetos em Django ainda mais completo e eficiente. Foi uma ideia sensacional, reunir em um único local tudo (ou quase tudo) que foi desenvolvido pela comunidade Django. O site está organizado em categorias (Apps, Frameworks, Projects, Utilites, etc) e a ordenação dos projetos é feita através de várias métricas, como número de downloads no Pypi, número de commits, número de seguidores, etc. Com isso é possível determinar se uma app tem seu desenvolvimento ativo, quantas pessoas contribuem, etc. Isso ajuda muito na busca e tomada de decisão. Confira o Django Packages em http://djangopackages.com/ O post Conheça o Django Packages apareceu primeiro em Christiano Anderson. -
Django quick tips – using template filters in your views
Django has some very useful template filters, like slugify, which turns a string with spaces into a suitable url slug, and title, which turns any string into title case. Have you ever wanted to use these in your views? All you need to do is add this import: from django.template.defaultfilters import * You can replace [...] -
Django full text search, purely Python
This is a Django full text search module, written purely in Python, using the power of regular expressions, and is fully compatible with Google App Engine server. The search module is given below, along with a code snippet to show how it works with Django or non-rel based GAE projects. The example has been simplified to show how it works with text search on the different 'Post' entries in a 'Blog' application. import re def get_keywords(query_string): """Accepts a search query string and returns a list of search keywords. """ # Regex to split on double-quotes, single-quotes, and continuous # non-whitespace characters. split_pattern = re.compile('("[^"]+"|\'[^\']+\'|\S+)') # Pattern to remove more than one inter white-spaces. remove_inter_spaces_pattern = re.compile('[\s]{2,}') # Return the list of keywords. return [remove_inter_spaces_pattern.sub(' ', t.strip(' "\'')) \ for t in split_pattern.findall(query_string) \ if len(t.strip(' "\'')) > 0] def get_results(objects, query, field_list): """Returns a QuerySet of filtered objects based on the 'query', upon a QuerySet of 'objects', on the fields specified by the list 'field_list'. """ # Create a string representing the actual query condition for filtering. condition = '' for field in field_list: condition = condition + 're.compile(query_pattern).search(obj.%(field)s) or ' % {'field': field} condition = condition[:-4] # Apply the …