Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Simple spam defense for Django comments
A simple way to block comment spam with the Django 1.0 contrib comments application. -
Emacs mode for dpaste.com
Since Paul Bissex announced the api for Django-powered dpaste.com last week I've had it's been on my todo list to make a emacs mode for posting pasties. -
How Django Works
This is my attempt to explain the inner working of Django. I've broken it down to multiple steps as an HTTP Request travels from your Browser to how your response is generated and back to your browser. I'll outline the steps here again:1. Standard Http Request Initiated http://mysite.com/hello/2. Your HTTP Server will load multiple copies of your django app ready to process requests.3. Django creates a Request Object representing your request and will filter them through multiple middlewares (python functions). These functions may modify the Request object or respond the request right there. Writing custom middlewares are simple.4. Django checks your defined URLs (Regular Expressions) to decide which function it must hand over the Request object to.5. This function takes the request object, much like your middlewares, except it Must return an Http Response Object. All your logic will go here. Django gives you a ton of other tools to access db, render your HTML files, etc to help you do all you need to do. You do not have to use them.6. The Response Object will once again go through all Middlewares in the reverse order, giving each middleware the option to modify the response if appropriate. -
Some great functions in django templates
In my quest to capitalize the title for my application, I found some great functionality in django's templates. To 'humanize' data there is contrib package called 'humanize'. For the docs you can find it here.For some built in functions look here. I really like some of the humanize functions after spending so much time to implement some of the functions found here. While django's template language might not be as powerful as others they sure have some pretty useful functionality here! -
Get User from session key in Django
Error emails contain session key When you get an error email from your Django app telling you someone got a server error, it’s not always easy to tell which user had a problem. It might help your debugging to know or you might want to contact the user to tell them you have fixed the problem. Assuming the user is logged in when they get the error, the email will contain the session key for that user’s session. The relevant part of the email looks like: <WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{ 'sessionid': '8cae76c505f15432b48c8292a7dd0e54'}, ... Finding the user from the session If the session still exists we can find it, unpickle the data it contains and get the user id. Here’s a short script to do just that: from django.contrib.sessions.models import Session from django.contrib.auth.models import User session_key = '8cae76c505f15432b48c8292a7dd0e54' session = Session.objects.get(session_key=session_key) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) print user.username, user.get_full_name(), user.email There it is. Pass in the session key (sessionid cookie) and get back the user’s name and email address. Plug: Get your own job board at Fuselagejobs -
Python 3.0 wydany!
Dziś w nocy została wydana trzecia wersja języka Python. Gratulujemy wszystkim programistom, którzy przyczynili się do tego wydarzenia. Informację o nowej wersji znajdziecie na http://www.python.org.pl/ Jak myślicie, kiedy Django przejdzie na nową wersję pythona? Czy będzie to najpierw... -
Generic inlines and Django history
The other day at work I stumbled across my first opportunity to use a relatively-new feature in the Django admin, one which turned what had looked like it would be a fairly nasty task into, basically, a five-minute job (plus staging, testing and deployment, of course, but that happens no matter how long it takes to develop the code). I’ll get to the specifics in a minute, but first I want to give a little ... Read full entry -
Generic inlines and Django history
The other day at work I stumbled across my first opportunity to use a relatively-new feature in the Django admin, one which turned what had looked like it would be a fairly nasty task into, basically, a five-minute job (plus staging, testing and deployment, of course, but that happens no matter how long it takes to develop the code). I’ll get to the specifics in a minute, but first I want to give a ... Read full entry and comments -
fez.djangoskel: Django projects and apps as eggs
I've made an initial release of fez.djangoskel, which provides simple paster templates for egg-based Django projects and applications. -
fez.djangoskel: Django projects and apps as eggs
This is just a brief note to say that I've release fez.djangoskel, a package which provides paster templates for creating egg-based Django projects and reusable applications. This is all part of my crusade to get the Django community to package software as eggs. As well as source and binary egg releases on PyPI, the code is available on GitHub (representing my first foray into git). The easiest way to get this is, as usual, with easy_install. (See my previous posts on how to set this up): easy_install fez.djangoskel Once that and its dependencies have installed, you should fine that paster can now create Django projects and apps: $ paster create --list-templatesAvailable templates: basic_package: A basic setuptools-enabled package django_app: Template for a basic Django reusable application django_project: Template for a Django project paste_deploy: A web application deployed through paste.deploy It's standard paste from here on in: to create a project, use: paster create -t django_project To create an app, use: paster create -t django_app Paster will then ask you a bunch of questions (the most crucial one being the name of your app/project!) and generate the file layout for you. I plan to do another release later this week which includes … -
fez.djangoskel: Django projects and apps as eggs
This is just a brief note to say that I've release fez.djangoskel, a package which provides paster templates for creating egg-based Django projects and reusable applications. This is all part of my crusade to get the Django community to package software as eggs. As well as source and binary egg releases on PyPI, the code is available on GitHub (representing my first foray into git). The easiest way to get this is, as usual, with easy_install. (See my previous posts on how to set this up): easy_install fez.djangoskel Once that and its dependencies have installed, you should fine that paster can now create Django projects and apps: $ paster create --list-templatesAvailable templates: basic_package: A basic setuptools-enabled package django_app: Template for a basic Django reusable application django_project: Template for a Django project paste_deploy: A web application deployed through paste.deploy It's standard paste from here on in: to create a project, use: paster create -t django_project To create an app, use: paster create -t django_app Paster will then ask you a bunch of questions (the most crucial one being the name of your app/project!) and generate the file layout for you. I plan to do another release later this week which includes … -
fez.djangoskel: Django projects and apps as eggs
This is just a brief note to say that I've release fez.djangoskel, a package which provides paster templates for creating egg-based Django projects and reusable applications. This is all part of my crusade to get the Django community to package software as eggs. As well as source and binary egg releases on PyPI, the code is available on GitHub (representing my first foray into git). The easiest way to get this is, as usual, with easy_install. (See my previous posts on how to set this up): easy_install fez.djangoskel Once that and its dependencies have installed, you should fine that paster can now create Django projects and apps: $ paster create --list-templatesAvailable templates: basic_package: A basic setuptools-enabled package django_app: Template for a basic Django reusable application django_project: Template for a Django project paste_deploy: A web application deployed through paste.deploy It's standard paste from here on in: to create a project, use: paster create -t django_project To create an app, use: paster create -t django_app Paster will then ask you a bunch of questions (the most crucial one being the name of your app/project!) and generate the file layout for you. I plan to do another release later this week which includes … -
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 фич, и я решил поделиться с вами неожиданно нахлынувшей на меня радостью :-). Заодно кто-то, как я, узнает новую для себя возможность Птона. Речь идет о тикете ...