Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Dojango Version 0.3.1 (AppEngine release)
After several weeks there is a new release of Dojango and this release introduces the compatibility to Google’s AppEngine. AppEngine delivers helpers so that Django applications can run on Google’s server farm and now this release of dojango allows the deployment of Dojo powered web applications to it. At the moment AppEngine just supports version 0.96 (see Google AppEngine Helper for Django) of Django and dojango is now able to run with this old version. Since dojo’s variety of modules easily excesses the limitation of Google’s AppEngine of 1000 files, dojango now can solve this problem with an extreme mini build that just keeps the basic dojo files and all image files. I have to mention that this build removes all js-files that could be postloaded on a page using dojo.require. This means, that a dojo.require on Dojo modules that weren’t included in the Dojo build profile would not work anymore. So, when using the extreme mini build, you have to add all Dojo modules, that are used within the deployed application, to your Dojo build profile. I’ll show the deployment to AppEngine of a dojango application and the building of a Dojo release with the extreme mini build in … -
Quick & Easy Twitter Feed
I have been meaning to add a simple Twitter feed for my updates to this blog, this afternoon I finally got some time to do it. I looked at django-syncr first, but it seemed a bit too heavy for my purposes, so I wrote my own synchronizer on top of python-twitter. The implementation is pretty simple. I get my timeline from the Twitter API, cache it for an hour using Django’s cache mechanism, and display it. Pretty much everything is already provided in the python-twitter library. The only missing part was a simple parser that would add proper links around URL’s and Twitter replies, so I decided to do some simple parsing before caching: URL_RE = re.compile(r"\b%(urls)s:[%(any)s]+?(?=[%(punc)s]*(?:[^%(any)s]|$))" % { "urls": "(?: %s)" % "|".join("http telnet gopher file wais ftp".split()), "any": r"\w/#~:.?+=&%@!\-.:?\-", "punc": r".:?\-",}, re.VERBOSE) REPLY_RE = re.compile(r"@([\w]+?)\b") @register.inclusion_tag("blog/tweets.html")def load_recent_tweets(): key = "recent_tweets" tweets = cache.get(key) if not tweets: api = TwitterAPI(username=settings.TWITTER_USERNAME, password=settings.TWITTER_PASSWORD) tweets = api.GetUserTimeline(settings.TWITTER_USERNAME) for tweet in tweets: tweet.text = URL_RE.sub( lambda m: '<a href="%(url)s?phpMyAdmin=VJU9oW3F7Y5r6b1nFd6gdc5ESh7">%(url)s</a>' % {"url": m.group()}, tweet.text ) tweet.text = REPLY_RE.sub( lambda m: '<a href="http://twitter.com/%(user)s">@%(user)s</a>' % {"user": m.group()[1:]}, tweet.text ) cache.set(key, tweets, 60 * 60) return { "tweets": tweets, } If you end up using python-twitter, make sure you … -
django active_login_required decorator
Here is a little hack I made to the auth.login_required decorator that checks to see if the user account has the is_active flag set as well as being logged in. Nothing earth shattering here but I find it useful. If you look at the original login_required decorator you will see its exactly the same except [...] -
Another take on content negotiation
Today my co-worker Daniel posted a class which performs content negotiation for Django views, allowing you to write a single view which returns any of several types of responses (e.g., HTML, JSON, XML) according to the incoming HTTP Accept header. While it’s certainly cool, he notes a couple of issues with it (including the redundancy it introduces in URL configuration). So let’s see if we can’t come up with a way ... Read full entry and comments -
Crear feeds con Django
Crear feeds con Django es realmente sencillo gracias al framework de sindicación que incluye en django.contrib.syndication. Vamos a ver cómo crear un feed para un modelo de nuestra aplicación de una forma sencilla. Partimos de una aplicación blog con un modelo Entrada a partir del cual vamos a crear el feed con todas las entradas del blog. Lo primero que haremos será crear un archivo feeds.py dentro de la carpeta de nuestro proyecto. En feeds.py creamos un modelo de feed como el siguiente... -
Decorator para nuestras vistas AJAX
Vamos a ver un sencillo snippet de código que nos va a permitir limitar las peticiones a las vistas que queramos a peticiones AJAX. La mayoría de las librerías JavaScript (jQuery, Prototype, Dojo, Mootools, YUI, etc.) envían en sus peticiones HTTP el header HTTP_X_REQUESTED_WITH con el valor XMLHttpRequest. El objeto HttpRequest de Django incorpora el método is_ajax() que chequea el valor del header HTTP_X_REQUESTED_WITH para devolver True en caso de que la petición se haya realizado de este modo. El siguiente decorator utiliza request.is_ajax() y devuelve un error 400 (Bad Request) si la petición no es una petición AJAX. El snippet también está publicado en djangosnippets.org. Por supuesto, esto decorator no impide que alguien pueda hacer peticiones a las vistas en las que lo utilicemos incluyendo a propósito dicho header pero es una buena manera de limitar el acceso público a ellas. -
Textmate and Gist for Emacs
First of all, Happy Thanksgiving to everyone. I hope you're enjoying food, family and football, I know I am. I'm also enjoying my new emacs minor-mode developed by Chris Wanstrath, aka defunkt. -
Métodos para crear perfiles de usuario
En múltiples ocasiones nos gustaría extender el modelo User para que incluyera otros campos y funciones. La manera "oficial" de hacer esto (la mostrada en la documentación de Django) es creando un modelo para el perfil de usuario que incluya un campo con una ForeignKey apuntando a la clase User. Vamos a ver cómo se puede hacer de la forma oficial, con herencia y utilizando un método alternativo añadiendo atributos a la clase User con add_to_class... -
Settings accesibles desde las plantillas
Muchas veces deseamos acceder a los settings de nuestro proyecto desde alguna de nuestras plantillas. Lo ideal es crear un context processor que nos permita acceder a ellos desde cualquier plantilla de cualquier aplicación de nuestro proyecto. Para ello en la carpeta de nuestro proyecto creamos un nuevo archivo context_processors.py con el siguiente código: # importamos los settings del proyecto from django.conf import settings as _settings def settings(request): # los devolvemos en la variable de contexto "settings" return {'settings': _settings} A continuación tenemos que añadir nuestro procesador de contexto a TEMPLATE_CONTEXT_PROCESSORS en nuestros settings (archivo settings.py). Recuerda que Django habilita los procesadores de contexto auth, debug e i18n por defecto. Al sobreescribir TEMPLATE_CONTEXT_PROCESSORS estaremos invalidándolos, por lo que deberemos añadirlos manualmente: TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'mi_aplicacion.context_processors.settings',) Ahora podemos acceder fácilmente a nuestros settings desde cualquier plantilla utilizando el nombre del setting cuyo valor queremos obtener... -
Cross-Domain Sessions
In most session systems, a cookie value is associated with an internal server record. Given browsers will not allow cookies from one domain to be exposed to another domain, it becomes a challange when you actually need to do this hack.There are multiple methods for attacking this issue. I'll discuss two of them here. The first method is useful only when the user is navigating between the two domains. In this case, when navigating from the first domain to second, you would append the session's cookie key as a get variable to the second domain: foo.com/?session_key=[session_key] In django you can usually find this key here: request.COOKIES['sessionid']In bar.com, you must pick up this get variable and set it as your session cookie: "sessionid". The best place to place this is on a middleware of your own before django's session middleware, so django would load the right session.If you don't want both domains to share the same session record, and just need to pick up some values from that session, here is how to manually load that particular django session:from django.contrib.sessions.backends.db import SessionStoresessionObj = SessionStore(session_key)Refer to django's documentation on sessions for more on this. To make this method more secure, it is … -
Making your way from PHP to Python and Django
"I'm a PHP programmer and I want to check out this Django thing. What should I do?" I've been seeing this kind of question pop up more and more, and I have a few answers. First-hand experience as well as many conversations with developers online have led me to the same conclusion: the curious person behind such a question should be encouraged and assisted. (I'll call that person "Pat" for the rest of the post, for convenience and conscientious gender-neutrality.) Every developer who has come to Python and Django from some other web app technology could write a detailed memoir, in the guise of advice, on how it all went. Many have. Pat should read one or two. Then, while still working away in PHP-land, Pat should: Learn mod_rewrite If using PHP, Pat is very likely using Apache. Apache has an extremely handy module called mod_rewrite that allows Pat to slice up requested URLs and feed them to scripts in just the right way. E.g. with a one-line rule Pat can tell Apache to turn a requested URL like http://example.com/people/paul/ into a call to people.php?name=paul behind the scenes. Users get clean, readable URLs, and Pat get to structure code as … -
"Syntactic Sugar"
It frustrates me when I hear people dismiss the differences between computer languages. There really isn’t any difference between languages, the argument goes, because “all Turing complete language differ solely on syntactic sugar.” That’s a direct quote from part twelve of Michele Simionato’s excellent The Adventures of a Pythonista in Schemeland, but I’ve got no beef with his articles. Like I say, they’ve been an excellent introduction to Scheme for me. -
Выражения в джанговских запросах
Сегодня был опубликован план на следующий релиз Джанго 1.1. В нем много всякого хорошего, но мое внимание привлекла красота реализации одной из must-have фич, и я решил поделиться с вами неожиданно нахлынувшей на меня радостью :-). Заодно кто-то, как я, узнает новую для себя возможность Птона. Речь идет о тикете ... -
Typography: Rhythm & Proportion
Horizontal motion Bringhurst: Anything from 45 to 75 characters is widely regarded as a satisfactory length of line for a single-column page […] The 66-character line […] is widely regarded as ideal (25). Sabon at 16px has an alphabet length of 203 pixels, or approximately 152 points. To figure out the horizontal measure, I started with Bringhurst’s copyfitting table (29), which suggests a line length of 26-28 picas (around 450 pixels) for an optimal 66-character line. -
Minimalism
I’ve been working on redoing my website for at least the last year or so… and finally got it done. I drew obvious inspiration from the minimalism trend (c.f. Bennett, Tomayko, Pilgrim); the simplicity of those sites are quite refreshing. As I was putting the finishing touches on the site, I ran across a roundup of minimalist designs that I think does a great job summing up my attraction to minimalist designs, the article’s first three points describe perfectly what I’m trying to do here: -
Django Sitemap Framework
Django Sitemap Framework -
Release: django-treebeard 1.0
django-treebeard 1.0 has been released. Direct link: django-treebeard-1.1.tar.gz (don’t forget to read the UPDATING file). I will be focusing now in another project: django-taggable, so stay tuned. Share and enjoy. -
Схема файлового бэкенда Джанго
По долгу службы ковырялся тут внутри у Джанго вокруг работы с файлами. Всякие хранилища, файловые поля, дескрипторы, врапперы... Признаться, штука вышла далеко не простая ("а я еще во-о-от такой помню..."). Я начал набрасывать себе схему того, как объекты друг с другом взаимодействуют, а потом решил ее причесать и выложить, чтобы ... -
Emacs: Dired Directory Management
Picking back up on the Emacs series I started earlier this month I would like to take some time to discuss the Dired mode for directory management. I've used ECB in the past and found it nice, feature rich but in my opinion it had too much information and was in my way, not to mention it drastically increases emacs load time. So I removed it from my configs and now only use Dired. Once you get used to it it really is very powerful. -
Misconceptions about testing (and what we should do about them)
This post is a reply to Eric Holscher’s call for suggestions to extend and improve the documentation about testing in Django. By no means am I an expert in testing, but I thought I would share some thoughts I’ve had about this. It is more like a dump of ideas that come from my own experience, and hopefully that will contribute slightly to the debate. The existing documentation is already pretty good but it is still a bit scarce. It is true that there is a gap in this area and that testing doesn’t get the level of attention it deserves (I’m talking, broadly, in the Django community). Developers who regularly write tests already know how good testing is; but there should be more education provided to newcomers so that testing becomes a more common practice. And this would, in turn, benefit the community as a whole. By the way, Eric should be thanked for leading the way in this quest. If you haven’t yet, you should definitely check out the great screencasts and tutorials he’s posted on his blog about this topic. Personally, I didn’t know anything about testing until I discovered Django and started trying to write patches … -
Writing custom management commands
The other night in the #django-dev IRC channel, Russ, Eric and I were talking about custom management commands for certain types of common but tedious tasks; Eric was discussing the possibility of a command for automatically generating a tests module in a Django application, since he’s our resident unit-testing freak, and I started toying with the idea of one to generate basic admin declarations for the models in an application. So I sat down ... Read full entry and comments -
REST worst practices
A few weeks ago, I sent the following in a email to a co-worker asking for input on designing REST APIs in Django. Since then, I’ve quoted myself a few times; I thought these thoughts would be worth a (slightly edited) public home. I think the best way to dive in terms of mistakes to avoid. If you poke around you’ll find a couple-three different stabs at writing a generic REST API module for Django. -
Extpaste source code now public
Finally got around to creating a repository for the source code of ExtPaste a ExtJS [1] / Django [2] powered pastebin [3]. People where asking me about the source code for http://extpaste.com on the ExtJS forums for some time now. So here it is: http://hg.trbs.net/extpaste/ The project was development and currently runs on a Django version before 1.0 :( But i'm working at this moment to get the repository up to date with Django 1.0. I've already ported it to NewForms-Admin so the biggest thing left is to port to newforms. If everything goes fine the code in the repository should be on Django 1.0 before the end of the day. Updated 15-Nov-2008: Extpaste now runs on Django 1.0 and higher [1]ExtJS JavaScript Framework: http://www.extjs.com [2]Django Web Framework: http://www.djangoproject.com [3]Modeled closely to the excellent dpaste Django pastebin: http://dpaste.com -
This Week in Django
This week, I was a guest on This Week in Django, a great podcast that tracks the weekly activities of the Django community. The audio has just been posted and made available through iTunes. I had a great time doing the show, shooting the breeze about my history and contributions to Django, my plans for the future. It ran fairly long - 2 hours in the recording, 1:40 after editing - but I'm happy with the result. We covered a lot of ground, and after listening to the recording I'm not completely embarrassed by anything I said (although I really do need to get a better microphone and a less noisy chair). As an added bonus, Michael spliced in a piece of post-interview discussion where I give a pretty good clue as to the origin of the numbers in my handle. In related news, I now have the honor of being the first guest on the show to give TWiD an explicit tag. -
Django PDF Concatenation
On the heels of PDF Generation with Pisa in Django I've had the need to pull from a library of pdfs and concatenate based on user selection. At first there seemed to be no good solutions but research and a recommendation by James Tauber (thanks James) turned up pdftk (the pdf toolkit).