Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Painless Amazon EC2 Backup
The past year on Amazon EC2 has taught me many things but first and foremost is back up consistently. I’ll say it again, back up consistently! Amazon even makes the backup almost painless, almost… Amazon has EC2 (the compute cloud) and S3 (the data repository). Out of the box you can back up from [...] -
Getting client OS in Django
Some times it can be useful to serve our site content with little differences depending on the visitor operating system. I really think it's a bad idea changing the content or doing some big changes, depending on it, but this post can be useful for it as well.So, while most time just some Javascript is used to customize user experience based on its operating system, few times it'll also be useful to do it in the server side.For those cases, here you've a simple context processor that will make available a template variable named "platform" which content can be "Linux", "Mac" or "Windows".import redef user_agent(request): ''' Context processor for Django that provides operating system information base on HTTP user agent. A user agent looks like (line break added): "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) \ Gecko/2009020409 Iceweasel/3.0.6 (Debian-3.0.6-1)" ''' print 'user_agent' # Mozilla/5.0 regex = '(?P<application_name>\w+)/(?P<application_version>[\d\.]+)' regex += ' \(' # X11 regex += '(?P<compatibility_flag>\w+)' regex += '; ' # U regex += '(?P<version_token>[\w .]+)' regex += '; ' # Linux i686 regex += '(?P<platform_token>[\w .]+)' # anything else regex += '; .*' user_agent = request.META['HTTP_USER_AGENT'] result = re.match(regex, user_agent) if result: result_dict = result.groupdict() full_platform = result_dict['platform_token'] platform_values … -
Updating CouchDB Views In Django
CouchDB views are a bit like stored procedures in a traditional database system. As with stored procedures it’s difficult to keep them in sync with your code, and to keep them in your version control system. In this article I’ll show you how you can use a django management command to update your views from [...] -
New CSS
I never thought that my personal blog would be useful to anyone except myself. I've not put a lot of effort into attracting traffic, but it's been trickling my way. I never really finished the templates and CSS for programmerq.net, so I spent a little time here and there over the past few days and added some CSS, and updated the templates to make the blog experience a bit nicer. I haven't added the template tags to turn on the calendar view in the sidebar, but I don't know how useful it would be anyway. I really enjoy the Django templating language. I was able to add the gravitar functionality to the comment system without modifying the source of the blog app that I use. All I did was create an app that had the template tag snippet, and a template for rendering. To get the gravitar to show up, I just copied the default comment rendering template out of the blog app, and told it to load the template tag and render in the appropriate place. As always, every site is under construction, and this site isn't an exception. I'm willing to take suggestions for improvement on my blog, … -
My Django-Compress Tasks
I am thoroughly impressed by django-compress as mentioned in yesterday's post. There are number of things that I'll be looking to add over the next couple of days that hopefully will make it even more useful for more than just me. I'll be committing these to my fork and submitting pull requests upstream to hopefully have them committing into the main repository. For output files, create the intermediary folders if they don't exist. Add a gzip option flag to the command to create gzip versions of the output files. Add a new css filter for replacing url() property contents with prefixes defined in configuration (allowing for the serving of content locally during development, and then off of CDN servers when deployed). Add a new version strategy, that will default to a prefix folder using today's timestamp (YYYYMMDD). Also allow for an optional parameter to the command line to override this default prefix. Add another "extra_context" variable called ABSOLUTE_URL to enable an override of both the PREFIX variable I included yesterday as well as the default MEDIA_URL. I need this so as to be able to put things like Google hosted libraries like jQuery, but also to have a quick and … -
My Django-Compress Tasks
I am thoroughly impressed by django-compress as mentioned in yesterday's post. There are number of things that I'll be looking to add over the next couple of days that hopefully will make it even more useful for more than just me. I'll be committing these to my fork and submitting pull requests upstream to hopefully have them committing into the main repository. For output files, create the intermediary folders if they don't exist. Add a gzip option flag to the command to create gzip versions of the output files. Add a new css filter for replacing url() property contents with prefixes defined in configuration (allowing for the serving of content locally during development, and then off of CDN servers when deployed). Add a new version strategy, that will default to a prefix folder using today's timestamp (YYYYMMDD). Also allow for an optional parameter to the command line to override this default prefix. Add another "extra_context" variable called ABSOLUTE_URL to enable an override of both the PREFIX variable I included yesterday as well as the default MEDIA_URL. I need this so as to be able to put things like Google hosted libraries like jQuery, but also to have a quick and … -
Convenciones de proyecto en Django
Django ofrece una flexibilidad muy grande a la hora de configurar nuestros proyectos permitiéndonos organizarlos con estructuras muy diversas. Esta flexibilidad permite que podamos adaptar Django a necesidades concretas pero por otro lado hace que mucha gente se pregunte cuál es la manera correcta de organizar la estructura de sus proyectos. Convenciones en Django, creado por Eric Holscher, pretende ser un punto de referencia sobre las mejores prácticas y convenciones en Django. Esto es una traducción al español de las convenciones sobre proyectos. -
Slughifi: slugs a prueba de caracteres internacionales
Slughifi es un código que mejora las características de la función slugify de django.template.defaultfilters. Soporta muchos más caracteres internacionales con todo tipo de acentuación. Mientras que slugify elimina todos estos caracteres al generar el slug, slughifi los reemplaza por caracteres no acentuados haciendo honor a su nombre al proporcionar slugs altamente fieles a la cadena sobre la que se aplica. Fue presentado hace bastante tiempo en este hilo de la lista de correo django-users y dí con él por casualidad. Desde entonces no he dejado de utilizarlo en mis proyectos. Slughifi parece no estar disponible en la página original en la que se encontraba. Sin embargo sí lo está en el trac de django-fr y también lo podéis bajar directamente desde aquí. -
django-multilingual syntax poll
Those days there is some activity in the django model translation area, specially for the two new projects that joined django-multilingual and transdb to achieve this: django-transmeta and django-modeltranslation.While there are some intentional differences among some projects (for example django-modeltranslation is the only one that can translate models without editing them), it would be great to merge all (or most) existing projects, and join the efforts to get our best application (and hopefully it'll worth to be included in Django itself).So, with the merge of those applications in mind, we're planning to create a branch on django-multilingual that will have the very best of each existing application, and any other cool idea.So if you have good Python/Django skills, and want to add some open source work in your CV... ;) join us now!Or if you are a potential user of this application, or you just think that your opinion is worth to be shared, please fill the MODEL SYNTAX POLL, or mail us with your ideas.Here there are simple sample for each option on the poll:class Translationclass MyModel(model.Model): my_field = CharField() class Translation(multilingual.Translation): my_i18n_field = CharField()custom fieldsclass MyModel(model.Model): my_field = CharField() my_i18n_field = TransCharField()separate modelclass MyModel(model.Model): my_field = CharField() my_i18n_field … -
The tools of choice
Well, we have decided which tools we are going to use for our semester project. The winners are: Eclipse with the following plugins: PyDev (For python Development) Subclipse (For SVN connectivity) And for our development framework (after a period of uncertainty): Django was the clear winner. PostgreSQL will be our DBMS. Eventually we’ll configure the Apache HTTP Server to work with mod_wsgi for Apache-Python interpretation. Shortly I’ll post on how to get all those working nice together. Until then. -
Scratching Django-Compact for Django-Compress
Last week I talked about a project I had started to build called, django-compact, whose goal it was to provide a build process for all the various CSS and Javascript files in a given project. I was quickly notified in via Will Larson on Twitter that I should checkout django-compress. I did. To say that I was following the same approach would be an understatement. Furthermore, this project was much further along than I was. I spent the better part of this morning getting a subsection of my project wired up to use it and am well satisfied. There was a small additional feature I wanted to add, so I forked the project and made the additions. I feel like the changes are non-breaking and generally useful and therefore hope to get them pushed upstream. The feature in question involves being able to have multiple MEDIA_URLs for different outputs. I call them PREFIXes. My approach was to patch the media_url function in compress.utils to accept defaulted argument called prefix. If prefix exists in a non-empty state, then it concatenates itself with the url argument, otherwise it concatenates with the settings.MEDIA_URL setting. Upstream in render_common I look for a dictionary key … -
Scratching Django-Compact for Django-Compress
Last week I talked about a project I had started to build called, django-compact, whose goal it was to provide a build process for all the various CSS and Javascript files in a given project. I was quickly notified in via Will Larson on Twitter that I should checkout django-compress. I did. To say that I was following the same approach would be an understatement. Furthermore, this project was much further along than I was. I spent the better part of this morning getting a subsection of my project wired up to use it and am well satisfied. There was a small additional feature I wanted to add, so I forked the project and made the additions. I feel like the changes are non-breaking and generally useful and therefore hope to get them pushed upstream. The feature in question involves being able to have multiple MEDIA_URLs for different outputs. I call them PREFIXes. My approach was to patch the media_url function in compress.utils to accept defaulted argument called prefix. If prefix exists in a non-empty state, then it concatenates itself with the url argument, otherwise it concatenates with the settings.MEDIA_URL setting. Upstream in render_common I look for a dictionary key … -
Adding a simple WYSIWYM Markdown editor to your models
I'm a Markdown fan. Period. Since I first discovered it some years ago, I've been using it for storing all my "output-to-HTML" texts. Blango, the blog engine I wrote for this site, uses Markdown for post contents. As I've said, I really like Markdown, but typing (and sometimes escaping) all those *[]() gets boring from time to time. I've been looking for something like a WYSIWYG editor for some time, but none of the available choices seemed good enough for me. However, I recently stumbled upon WMD. So, what's WMD and why should I care? In the author's own words: So WMD is something new: a Wysiwym Markdown editor. Wysiwym stands for What You See Is What You Mean. WMD produces clean semantic HTML, leaving presentation details like fonts and colors up to style sheets. But you're not left in the dark about cosmetics; as you type, WMD's live preview shows you exactly what your text will look like after the current styles have been applied. Markdown is a simple markup language that's as easy to read and write as plain-text email. WMD uses Markdown as an input format, converting it into HTML behind the scenes. You can also mix … -
Ottawa Python Authors Group Meeting
The Ottawa Python Authors Group is having a meeting tomorrow (Monday) and Michael Soulier will be presenting talks on concurrency in Django, and an Introduction to Git. It has been a while since the last meeting and this promises to be a good one. -
Templayer 1.5.1 Released
This release fixes a number of bugs in the 1.5 release: Templayer Home Page Download Tarball -
Three New Debian Django Packages
Recently my employer, credativ UK1 have been kind enough to allow me to spend some time working on Debian packaging from some Django apps we've started using internally. Chris Lamb was kind enough to sponsor the upload of these packages. Django developers, this means that if you are running a Debian GNU/Linux machine2, you can type: apt-get install python-django-<app name> and you will have it installed for all users on the system. You won't need to mess around with any Python packaging systems, or modify your environment to be able to use them. So, what are the packages and why are we using them? django-tinymce django-tinymce is a Django app providing integration with TinyMCE, a pure JavaScript rich text editor. It provides a widget that can be used within forms, and can also easily be used within views. It integrates with django-filebrowser, which I will mention below. django-cms integrates with django-tinymce to provide a rich text editor for pages within it. As our website content will have to be maintained by people who may have little or no experience with HTML (or Markdown or anything else that isn't Word), this is obviously desirable. django-filebrowser django-filebrowser is a Django app that … -
Añadir encoding UTF-8 a nuestros archivos .py
Esto es una pequeña ayuda para aquellos que empiezan con Python/Django. A menudo utilizamos variables o comentarios en nuestro código python que tienen caracteres acentuados u otros que no son ASCII. Estos caracteres causan errores de sintaxis como el siguiente: SyntaxError: Non-ASCII character '\xc3' in file /proyecto/app1/models.py on line 5, but no encoding declared; Para solucionarlo nos basta con definir el encoding a utilizar insertando la siguiente línea de texto al comienzo de nuestro archivo .py: # -*- encoding: utf-8 -*- Con esto estaremos especificando que nuestro archivo .py está codificado en UTF-8. La codificación UTF-8 bastará en la mayoría de los casos pero también puedes utilizar otras codificaciones. Aquí tienes más información respecto a este tema. -
Slow Django Requests
So I've had a slice with slicehost for about a year and a half now. I love all the things I can do with my very own relatively cheap server on the Internet. I started out with a 256 slice, and then I talked my wife into upgrading to a 512. I kept putting more things on my server because it was so convenient, and fun to have a 100% static IP on the internet. I've started running my own mail server, and slowly I've been moving all my personal sites to Django. I even host a website on my slice for a small fee. After a little while, I was curious as to why all my Django apps seemed to run so slowly. I don't use my own website very often, so I didn't notice the slowness creeping in. Running top revealed that I was using all of the ram on my 512 slice, and I had about half a gig in swap. I won't be able to talk my wife into moving to yet another price double on my slice, so I decided to try to combat this problem with smarts rather than money. Django apps seemed to … -
Representar campos con choices en nuestras plantillas
Cuando usamos un campo con diferentes opciones (choices) en nuestro modelo utilizamos una lista de elementos cada uno con el valor real que se almacenará en la base de datos seguido por la representación legible del dato. Un ejemplo es el siguiente modelo ... Suponiendo que tenemos una plantilla que recibe un objeto Artista en la variable {{ artista }} normalmente accedemos al valor de sus campos mediante {{ artista.campo }}. Pero al estar usando choices con {{ artista.estilo }} obtendremos el valor almacenado en la base de datos en vez de su representación legible definida en ESTILOS_CHOICES. ¿Cómo acceder a la forma legible del dato? ... -
Instalar PIL en Mac OS X Leopard 10.5.6
Al instalar Django en Mac OS X, si utilizamos ImageField en nuestros modelos necesitaremos PIL (Python Imaging Library), la librería de tratamiento de imágenes para Python. Tras probar con distintos métodos que no han tenido éxito he encontrado un post que explica de una forma sencilla cómo hacerlo. Estos son los pasos a seguir. -
Django-Compact Updates
Getting back into the swing of things on django-compact today: Today's Commits Got concatenation working for both js and css Added minification support via YUI Compressor This second item in the list leads me to a question about best practices when creating a re-distributable Django app. Minification support is an optional flag passed at run time to build your css/js: ./manage.py compact --minify If specified, it will run the concatenated files through the YUI Compressor minifier. Since this tool is java based, and not python :(, I decided to include the jar file in a lib folder under the application folder. I then created a module called yui.py and encapsulated the shell out via Popen in a python class called Compressor. This does assume that the java executable is in your path and is of a version greater than 1.4 (YUI Compressor requires at least 1.4). The question I have is, is there a best practice of where and when to include binaries such as this? I feel that this is pretty clean in that I construct the path to the jar dynamically at run time so i don't assume any particular install location. I could do more up front … -
Django-Compact Updates
Getting back into the swing of things on django-compact today: Today's Commits Got concatenation working for both js and css Added minification support via YUI Compressor This second item in the list leads me to a question about best practices when creating a re-distributable Django app. Minification support is an optional flag passed at run time to build your css/js: ./manage.py compact --minify If specified, it will run the concatenated files through the YUI Compressor minifier. Since this tool is java based, and not python :(, I decided to include the jar file in a lib folder under the application folder. I then created a module called yui.py and encapsulated the shell out via Popen in a python class called Compressor. This does assume that the java executable is in your path and is of a version greater than 1.4 (YUI Compressor requires at least 1.4). The question I have is, is there a best practice of where and when to include binaries such as this? I feel that this is pretty clean in that I construct the path to the jar dynamically at run time so i don't assume any particular install location. I could do more up front … -
My Latest Project: BackTrac Backup System
My life has been pretty busy as of late, mostly with a new project I am working on called BackTrac. I am developing a network backup solution, written entirely in Python - using the Django framework as a front-end web interface.This came at quite a good time, as I've been asked to give a presentation [...] -
Numeric IP field for Django
Some time ago I needed to add an IP field to my model with more records (some hundred thousands). I was going to just add Django's IPAddressField, but I realized that it stores the data as text on the database, and I didn't like the idea.Basically, and IP address is just 4 bytes of data, but it's text representation can use between 7 and 15 bytes. That's not a big different when your model will have few rows, but it's a different when you'll have a huge set of IP addresses, and specially if you want to join tables by it.The only inconvenient of storing the IPs as numbers is that are not human readable if you want to check them directly to database.So, here you have my code that can be used as a replacement of IPAddressField:import IPy from django.db import modelsfrom django import formsfrom django.utils.translation import ugettext as _def _ip_to_int(ip): return IPy.IP(ip).ipdef _int_to_ip(numeric_ip): return IPy.IP(numeric_ip).strNormal()class IPFormField(forms.fields.Field): def clean(self, value): try: _ip_to_int(value) except ValueError: raise forms.ValidationError, \ _('You must provide a valid IP address') return super(IPFormField, self).clean(value)class IPField(models.fields.PositiveIntegerField): ''' IP field for django for storing IPs as integers on database (Django's field IPAddressField stores them as text) ''' __metaclass__ … -
Creating Django Management Commands
Creating a website with Django is great fun, but eventually you’ll need to write a tool to clean up you data, expire old users or one of the myriad of other administration tasks that are involved with running a website. You’ll be very used to using manage.py to create your database and to run your [...]