Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Aplicar filtros a annotate() al usar Count()
A veces queremos utilizar la función de aggregación annotate() y aplicar filtros al modelo que se encuentra dentro de la misma, pero no es posible hacerlo con el ORM de Django actualmente. En este caso la solución pasa por usar la función extra() del ORM de Django para incluir SQL propio... -
Descargar y guardar archivos por su URL
Vamos a ver cómo guardar un archivo a partir de su URL. Este método nos permitirá descargar y guardar cualquier archivo de Internet y nos servirá tanto para campos ImageField como FileField... -
Crear gráficas estadísticas con Django y Google Visualization API
Vamos a ver cómo combinar django-qsstats para generar estadísticas y Google Visualization API para representarlas gráficamente. django-qsstats permite obtener estadísticas agregadas sobre querysets de forma sencilla. Vamos a crear una vista que nos dé el número de usuarios registrados cada día para los últimos 14 días... -
Agrupar mediante el templatetag {% regroup %} con una función propia
El templatetag {% regroup %} del lenguaje de plantillas de Django nos permite agrupar un listado de objetos por una propiedad. Generalmente utilizamos un campo por el que agrupar pero también podemos utilizar una función propia para agrupar los objetos como queramos. Vamos a ver un ejemplo sencillo en el que agruparemos un listado de artículos por su fecha de publicación, dividiéndolos en artículos publicados "Esta semana", "La semana pasada" y "Hace X semanas" ... -
Trabajar con slugs en URLs
Una de las cosas que los buscadores tienen en cuenta para establecer la relevancia de sus resultados son las palabras que aparecen en las URLs. Por eso conviene que las URLs de nuestros objetos incluyan un slug que los represente. -
First Satchmo Sprint
We are going to have the first official Satchmo sprint on January 2nd, 2010. Unless we have critical mass in one location, this will be a virtual sprint in the hopes of getting maximum participation from the community. -
Heading to Pycon 2010
I will be heading out to Pycon tomorrow. If you're going to be there, stop by and say hi. I will even be presenting on Friday afternoon so I look forward to meeting more folks in the community. -
Development workflow with mercurial, bitbucket and fabric
Now that I've been using mercurial and bitbucket for a while, I thought it might be useful to describe the development workflow I follow for using mercurial for branching, merging and local development. I'll also talk a bit about using fabric for deployment. -
Satchmo 0.9.1 Released
After almost 7 months of development work, Satchmo 0.9.1 is released. This version of Satchmo has many improvements and updates over the old version. This is a summary. The rest of the article is posted on the blog. -
DjangoCon Europe 2011
Se ha anunciado que la DjangoCon Europe 2011 tendrá lugar en Amsterdam del 6 al 10 de Junio. La conferencia será del día 6 al 8 y los días de sprint el 9 y 10 de Junio. Hay más detalles en la web oficial del evento. -
Satchmo development with virtualenv
By now, most people doing Django development should be familiar with pip, virtualenv and virtualenvwrapper. This post shows how I use these tools to maintain my local development environment for Satchmo. -
BarDiver.com Launches
Back in September I said that I was working on a surprise project. Well today I am happy to announce that BarDiver.com has officially launched. BarDiver.com is a community driven search site to help you find local bars that have the features and atmosphere you like. For this first release I am keeping BarDiver.com focused on Colorado only. If that is a success and I get interest to open BarDiver.com for another city/state I will absolutely do that. So please, check out the site and if you think your area could use BarDiver.com, let me know. BarDiver.com is built using the Django web framework. Django was instrumental in getting the site up fast. I cannot get over how great Django is to work with. I was able to use many of the goodies built into Django instead of writing them (again) myself. Some of these things are the authentication, comments, sites, flatpages and of course the admin user interface. I am really looking forward to the many cool new things that are being worked on in the seperate Django branches, such as Multiple Database Support, and Generic Authorization. I hope you enjoy BarDiver.com Dive In. -
Django in June
This is going to be one busy weekend. Friday after work I am going to Coors Field to watch the Rockies vs. the Devil Rays. I am driving straight from the game to DIA to catch the red eye into Logan where I will pick up my rental car and go directly to the Django in June un-conference. I am really looking forward to this. It will be great to meet some of the great people in the Django community. I also hope to meet some people in Boston that might be interested in helping me populate boston.bardiver.com with some more great bars. To ensure that this happens I will also be bringing with me some BarDiver.com Schwag to give out. ;) Once the conference is done with I will be driving up to New Hampshire to play golf with my Dad on Fathers Day. This should be a lot of fun. This will be the 3rd time I have played this year. After that and a quick visit with my Grandmother, I will be driving back into Boston to catch my flight back to Denver. Sunday night I might actually get 8 hours of sleep before I have to … -
Intense Debate Import Hack
Recently I wanted to try out the Intense Debate commenting system on this blog. I didn't want to lose all the comments that I had already and Intense Debate only supports importing comments from Blogger, etc but not custom blog software. Since I wrote this blog using the Django framework using django.contrib.comments I needed to come up with my own solution. It only took one Tamper Data request to see how an anonymous comment was posted into the Intense Debate system. A few minutes later I had a script to import my old comments into Intense Debate. intenseDebate.py import intenseDebate intenseDebate.postComment(blogpostid="", acctid="", anonName="", anonEmail="", \ anonURL="", comment="") blogpostid is the unique Intense Debate postId. You can find this easily on any Intense Debate powered page using the firebug dom tab. The key to look for is "IDCommentScript". acctid is your Intense Debate accountId. This can also be found using the firebug dom tab. The key to look for is "IDWUserWidget.acctid" anonName is the name of the commenter anonEmail is the commenters email address anonURL is the commenters web address comment is the text of the comment This method of importing comments does have it's problems. Manual process to get the … -
A simple Django life stream
After reading Ryan Bergs' "The basics of creating a tumblelog with Django" (part1) and (part2), I realized that I wanted a similar tumblog/life stream but I didn't want to have to go through all the work of saving those objects to the database. After all, isn't all that data already stored in their respective systems. And since I am using FriendFeed, which is again duplicating all that data, I don't want to be duplicating it yet another time. That's when the light bulb went off. Using the FriendFeed API and a bit of caching I can pull in my lifestream from FriendFeed using only a custom tag. So I came up with what I call lifefeed Just add "lifefeed" to your installed apps and you can now do this from any template {% load lifefeed %}{% load cache %} {% cache 900 friendfeed %} {% lifefeed "YOUR FRIEND FEED USERNAME" %} {% endcache %} You can use the default friendfeed.html template that comes with lifefeed or use your own. You will most definitely want to use your own CSS to style the items since I am no CSS guru. lifefeed is very simple right now but I would like to … -
Pinax Developer Quickstart
At PyCon I helped a group of people get a Pinax development environment set up. Many People were not yet familiar with the whole virtualenv and pip workflow, so I thought I would put up the steps I use to get Pinax up. -
Satchmo product images
Templatetag for Satchmo creates unordered list for product images. CSS can be applied to customize output. from django import template from satchmo.product.models import Product from satchmo.thumbnail.templatetags.satchmo_thumbnail import thumbnail try: from xml.etree.ElementTree import Element, SubElement, tostring except ImportError: from elementtree.ElementTree import Element, SubElement, tostring register = template.Library() default_opts = { 'thumbnail': 'width=280', 'start': 0 } class ProductGalleryNode(template.Node): def __init__(self, product, **opts): self.product = template.Variable(product) self.opts = default_opts self.opts.update(opts) def render(self, context): actual_product = self.product.resolve(context) images = actual_product.productimage_set.all() start = int(self.opts['start']) if len(images) <= start: return ("") root = Element("ul", {'class': self.opts.get('class', '')}) for (i, pic) in enumerate(images[start:]): li_attr = {'class': 'first'} if not i else {} li = SubElement(root, 'li', li_attr) link = SubElement(li, 'a', {'href' : pic.picture.url}) caption = pic.translated_caption() src = thumbnail(pic.picture.url, self.opts.get('thumbnail')) img = SubElement(link, 'img', {'src': src, 'alt': caption, 'title': caption}) return tostring(root, 'utf-8') @register.tag def product_gallery(parser, token): """ Returns an unordered list of image thumbnails for product. Usage: {% product_gallery product %} {% product_gallery product thumbnail="width=280"%} {% product_gallery product start=1%} {% product_gallery product class=galeria%} """ kwargs = {} bits = token.split_contents()[1:] product = bits[0] for bit in bits[1:]: arg, val = bit.split("=", 1) kwargs[str(arg)] = val.strip('"') return (ProductGalleryNode(product, **kwargs)) -
Switch between django trunk and stable versions
This is snippet that I use to switch development with Django between 1.0 and trunk versions: #!/bin/sh rm /Library/Python/2.5/site-packages/django if [ "$1" = "" ]; then echo "Django 1.0" ln -s LOCATION_OF_SOURCE_CODE/django-1.0/django /Library/Python/2.5/site-packages/django else echo "Django trunk" ln -s LOCATION_OF_SOURCE_CODE/django-trunk/django /Library/Python/2.5/site-packages/django fi $ ~/djchange.sh Django 1.0 $ django-admin.py --version 1.0-final-SVN-8977 $ ~/djchange.sh trunk Django trunk $ django-admin.py --version 1.1 alpha 1 SVN-10065 Also check that django-admin.py is symbolic link to /Library/Python/2.5/site-packages/django/bin/django-admin.py -
Django testshell
It is usable if you want to play with test database. See also testserver docs from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list help = 'Runs a Python interactive interpreter with test database and data from the given fixture(s).' args = '[fixture ...]' requires_model_validation = False def handle(self, *fixture_labels, **options): from django.core.management import call_command from django.db import connection verbosity = int(options.get('verbosity', 1)) # Create a test database. db_name = connection.creation.create_test_db(verbosity=verbosity) # Import the fixture data into the test database. call_command('loaddata', *fixture_labels, **{'verbosity': verbosity}) call_command('shell') -
Use unicode in doctests
Use hex representation, double quote slashes in expectation. Do not use print in doctests . """ >>> s = u"šđčćž" >>> s u'\\xc5\\xa1\\xc4\\x91\\xc4\\x8d\\xc4\\x87\\xc5\\xbe' """ -
Django set language for admin
If you want to explicitly set language for django admin section use this middleware: from django.conf import settings from django.utils import translation class AdminLocaleURLMiddleware: def process_request(self, request): if request.path.startswith('/admin'): request.LANG = getattr(settings, 'ADMIN_LANGUAGE_CODE', settings.LANGUAGE_CODE) translation.activate(request.LANG) request.LANGUAGE_CODE = request.LANG Then put somewhere in settings.py: ADMIN_LANGUAGE_CODE=’it’ and add middleware: MIDDLEWARE_CLASSES = ( ... 'utils.multilang.middleware.AdminLocaleURLMiddleware', .... -
Django-simpleadmindoc
I started this project as I needed to deliver help and documentation for django-admin on client website and admindocs seems more oriented to developers than to users. http://github.com/bmihelac/django-simpleadmindoc -
Django time widget with custom time shortcuts
This small javascript snippet replaces standard django clock shortcuts Midnight, Noon, Now & 6am with various time increments . $(window).load(function() { $('.timelist').each(function(num, el) { time_format = get_format('TIME_INPUT_FORMATS')[0]; $(el).html(''); for (i=8; i<20; i++) { var time = new Date(1970,1,1,i,0,0); lnk = "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '" + time.strftime(time_format) + "');" $(el).append('<li><a href="'lnk'">' + time.strftime('%H:%M') + '</a></li>'); } }); }); This snippet use JQuery which is available with Django 1.2. (dev at time of writing)Also, javascript should be loaded after DateTimeShortcuts.js but unfortunately I didn’t find a better way to achive this but to add in modified base admin site templates/admin/base_site.html. If you have any suggestion for improvement, let me know in comments. -
Do not use appname as templatetags module
This is the second time I created same error writing templatetags, so it is about time to document it. This is the bad layout for poll app. polls/ __init__.py models.py templatetags/ __init__.py polls.py views.py Instead of polls.py it should be polls_tags.py or something other different from appname. Whats going on? polls.py would define polls module and it would not be possible to import other modules from original polls application. For example the code bellow would throw ImportError: No module named models #polls.py from django import template from polls.models import Question register = template.Library() -
Handling i18n in Django projects
Given the following premises: Some 3rd party apps do have translations for language that we need and some do not. Translations for some apps maybe poor or just inadequate We don't always have write access for some apps catalogs Our goal is to offer website editor access for easily managing all important translations. Example project setup As a example project let say we want to build small website with FAQ section in Slovenian and Deutsch language. To manage questions and answers we want to use django-faq app. We would include Django Admin and Rosetta applications to allow administrator to easily manage content and translations on the website. Our directory structure looks like this: example.com/ website/ custom/ settings.py urls.py requirements.txt Note that we won't copy django-faq (or any other external apps) into our project directory, as it would made it harder to receive updates and bugfixes. Beside that we don't want it to clutter our source version control system with other projects. We would rather made it available on python-path by using pip, easy_install or symlinking it to site-packages directory. Ideal workflow Looking at the faq app we notice that it already have translations for Deutsch language but not for Slovenian …