Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
backbonejs django generic view
I recently had a chat with @Deacalion about backbonejs who recommended I had a look into it. So I’ve spent some time learning backbonejs whilst keeping in mind how I might use it with my own Django based projects. The questions I wanted to answer are as follow. Do I want to use backbonejs and if so [...] -
The Cloud is Not For You
Update: Did I hurt your feelings with this post? Read Scaling your Clouds so you can rage even more. Well, maybe not specifically you, but the mass that screams it will solve their problems. It’s been a fun year so far. There’s been exciting things happening both for me personally, as … -
The Cloud is Not For You
Update: Did I hurt your feelings with this post? Read Scaling your Clouds so you can rage even more. Well, maybe not specifically you, but the mass that screams it will solve their problems. It's been a fun year so far. There's been exciting things happening both for me personally, as well as a... -
Quick deploy with Chef-Solo and Git
Using Chef with Chef-Server requires to install a lot of weird stuff on your server; even after you manage to set it up, you're not safe from its quirks. However, you don't really need a chef-server to set up and update your machines - you can get away with chef-solo and git. -
The Organism Application
I had an email from a self-confessed django beginner, asking for some assistance. Here is my solution, as I worked through it. ## The Application ## The application is designed to allow tracking information related to identifying various organisms. An organism may have many identifying features, such as on a tree, the height, and the leaf morphology, or on a bird, the colour of the feathers, size of the egg and so on. To make it simpler for the users, it would be useful to classify organisms as belonging to a type, which can then be used to limit the available choices of identifying features: if an organism is a bird, then we only show those features that make sense for a bird. To do all of this, we can have a class structure that looks somewhat like: {% highlight python %} # models.py from django.db import models class OrganismType(models.Model): description = models.CharField(max_length=200) class IdentificationField(models.Model): type = models.ForeignKey(OrganismType, related_name='id_fields') name = models.CharField(max_length=200) class Meta: unique_together = ('type', 'name') class Organism(models.Model): common_name = models.CharField(max_length=200) latin_name = models.CharField(max_length=200, unique=True) type = models.ForeignKey(OrganismType, related_name='organisms') class IdentificationDetail(models.Model): organism = models.ForeignKey(Organism, related_name="id_details") field = models.ForeignKey(IdentificationField) description = models.CharField(max_length=250) class Meta: unique_together = ('organism', 'field') {% … -
Karen Tracey to Deliver Keynote at DjangoCon Europe 2012
I am very proud to announce that Karen Tracey, Lead Developer at Caktus and Django Core Developer, will be delivering a keynote address at DjangoCon Europe next week. This will be Karen's first speech to the Django community, of which she has been an exemplary member since 2006. DjangoCon Europe is the central meeting point ... -
Dummies doing (even more) dummy things
This is a follow-up to the Dummies doing dummy things post. I originally posted info about this update on the mailing list some time back, but it has been pointed out to me that it might be a nice thing to put on the dev blog too since it's well, related to development!I have been at it with further profiling in Evennia. Notably even more aggressive on-demand caching of objects as well as on-object attributes. I found from profiling that there was an issue with how object access checks were done - they caused the lock handler to hit the database every lock check as it retrieved the needed attributes.Whereas this was not much of a hit per call, access checks are done all the time, for commands, objects, scripts, well everything that might need restricted access. After caching also attributes, there is no need to hit the database as often. Some commands, such as listing all command help entries do see this effect (although you still probably wouldn't notice it unless you checked before and after like I did). More importantly, under the hood I'm happy to see that the profile for normal Evennia usage is no longer dominated by … -
Django class based views in action - forms handling
Django class based views offer a wide range of features - supporting forms, objects lists and many more. In this article I'll show some of the class based views in action - those related to forms and object lists. -
Querysets aren't as lazy as you think
It should be reasonably well-known by now that querysets are lazy. That is, simply instantiating a queryset via a manager doesn't actually hit the database: that doesn't happen until the queryset is sliced or iterated. That's why the first field definition in the form below is safe, but not the second: class MyForm(forms.Form): my_field = forms.ModelChoiceField(queryset=MyModel.objects.all()) my_datefield = forms.DateTimeField(initial=datetime.datetime.now()) Even though both elements are calling methods on definition, the first is safe because the queryset is not evaluated at that time, whereas the second is not safe because it is evaluated at that time, and therefore remains the same for the duration of the current process (which can be many days). For the record, you should always pass the callable: initial=datetime.datetime.now, without the calling brackets. Now, there are a couple of gotchas here. It is perfectly possible to define manager methods that are not safe to use in places like the queryset argument to the first field above. Here's an example: class PublishedManager(models.Manager): def get_query_set(self): return super(PublishedManager, self).get_query_set().filter( published_date__lte=datetime.datetime.now()) Clearly, this is an attempt to create a manager that automatically filters items which have been published. In the normal course of calling this in a view, it will work exactly … -
Querysets aren't as lazy as you think
It should be reasonably well-known by now that querysets are lazy. That is, simply instantiating a queryset via a manager doesn't actually hit the database: that doesn't happen until the queryset is sliced or iterated. That's why the first field definition in the form below is safe, but not the second: class MyForm(forms.Form): my_field = forms.ModelChoiceField(queryset=MyModel.objects.all()) my_datefield = forms.DateTimeField(initial=datetime.datetime.now()) Even though both elements are calling methods on definition, the first is safe because the queryset is not evaluated at that time, whereas the second is not safe because it is evaluated at that time, and therefore remains the same for the duration of the current process (which can be many days). For the record, you should always pass the callable: initial=datetime.datetime.now, without the calling brackets. Now, there are a couple of gotchas here. It is perfectly possible to define manager methods that are not safe to use in places like the queryset argument to the first field above. Here's an example: class PublishedManager(models.Manager): def get_query_set(self): return super(PublishedManager, self).get_query_set().filter( published_date__lte=datetime.datetime.now()) Clearly, this is an attempt to create a manager that automatically filters items which have been published. In the normal course of calling this in a view, it will work exactly … -
RQ tips
Note Obsolete This article was written for RQ 0.1.2, which is old. The RQ API has changed a little bit and the eager mode was added in RQ 0.3.1. This entry hasn't been updated to match the API changes so be prepared to dig if the code snippets don't work out-of-the-box. I just added RQ as an asynchronous tasks manager to my current project. If you haven't heard of RQ yet, it's a simpler alternative to Celery for executing asynchronous tasks. Eager mode If you're familiar with Celery, you probably know it has an eager mode that makes tasks synchronous, making things like testing and local development a little bit easier. RQ doesn't have this feature, however it can be added by simply wrapping its queuing mechanism: import redis import rq from django.conf import settings def enqueue(function, *args, **kwargs): opts = getattr(settings, 'RQ', {}) eager = opts.get('eager', False) if eager: return function(*args, **kwargs) else: conn = redis.Redis(**opts) queue = rq.Queue('default', connection=conn) return queue.enqueue(function, *args, **kwargs) Here we're using the Django settings to determine whether eager mode is enabled via the RQ dictionary, and this setting also lets us specify the Redis connection options (hostname, port, DB, etc.). The minimal settings.py … -
Goodbye iOS, hello Android
My iPod touch died and I got an Android phone. -
WatPy: Waterloo Region Python Group
Come hear what the newest tech group in Kitchener-Waterloo has to say at our first Peer 2 Peer event. Thursday June 7th, 6:30pm at the Communitech Hub. Featuring Brydon Gilliss and a handfull of lightning speakers. More Information | Register WatPy We started meeting 4 months ago, and so far the response has been awesome. Our focus is building community, teaching Python and talking about the language we all like a heck of a lot. I am proud to be part of the beginnings of the community group. Python is a diverse language with uses for web development, scientific computing, psychology and wrapping C libraries. All of these activities are already represented by our group. Diversity complements a changing and innovative Region. Beyond reaching out and building the community itself, I want to work with other community groups to help built tools which make running community groups easier. If you are interested contact me. -
WatPy: Waterloo Region Python Group
Come hear what the newest tech group in Kitchener-Waterloo has to say at our first Peer 2 Peer event. Thursday June 7th, 6:30pm at the Communitech Hub. Featuring Brydon Gilliss and a handfull of lightning speakers. More Information | Register WatPy We started meeting 4 months ago, and so far the response has been awesome. Our focus is building community, teaching Python and talking about the language we all like a heck of a lot. I am proud to be part of the beginnings of the community group. Python is a diverse language with uses for web development, scientific computing, psychology and wrapping C libraries. All of these activities are already represented by our group. Diversity complements a changing and innovative Region. Beyond reaching out and building the community itself, I want to work with other community groups to help built tools which make running community groups easier. If you are interested contact me. -
Creating stacked bar charts with Flot
Creating stacked bar charts with Flot Flot is a powerful JavaScript plotting library for jQuery. It uses <canvas> tag for creating beautiful graphical plots. Out of the box it supports lines, points, filled areas, bars and any combinations of these. With plugins you get pie charts, stacked charts and more. Today we’ll take a look at Flot’s stacked charts support. The first thing you must notice is that you have to pass the data in the right format. Also, Flot has a bug in creating stacked charts that may require some tinkering with Flot’s code. Luckily there’s a patch available. Prerequisites Download the Flot package and add jQuery, Flot’s core .js and stacked charts plugin to your page. excanvas.js is needed for legacy IE support. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17<head> <link rel="stylesheet" type="text/css" href="style.css"> <!--[if lte IE 8]> <script type="text/javascript" src="excanvas.min.js"></script> <![endif]--> </head> <body> <div id="plot"></div> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.flot.js"></script> <script type="text/javascript" src="jquery.flot.stack.js"></script> <script type="text/javascript"> // your code goes here... </script> </body> The package also contains the minified versions, so in production it may be advisable to use them instead. Basic usage The chart is created … -
Django's CBVs were a mistake
See end for updates to my ideas on this I've written before about the somewhat doubtful advantages of Class-Based Views. Since then, I've done more work as a maintenance programmer on a Django project, and I've been reminded that library and framework design must take into account the fact that not all developers are experts. Even if you only hire the best, no-one can be an expert straight away. Thinking through things more from the perspective of a maintenance programmer, my doubts about CBVs have increased, to the point where I recently tweeted that CBVs were a mistake. So I thought I'd explain my reasons here. First, I'll look at the motivation behind CBVs, how they are doing at solving what they are supposed to solve, and then analyse the problems with them in terms of the Zen of Python. What problems do CBVs solve? Customising generic views People kept wanting more functionality and more keyword arguments to the list_detail views (and others, but that those especially, as I remember). The alternative was large copy-and-paste of the code, so people were understandably wanting to avoid that (and avoid writing any code themselves). So, we replaced them with classes that allows … -
Fabric & Django
Or how automate the creation of new projects with simple script Preface: Do you remember all this tiny little steps that you have to perform every time when you start new project – create virtual environment, install packages, start and setup Django project? Kind of annoying repetition, isn’t it? [...] -
Pingdjack
Понадобился мне недавно pingback-сервер, и я, посмотрев на django-pingback, в приступе NIH-синдрома написал своё приложение — pingdjack. За название спасибо Михаилу Лукьянченко. Отмазка Более-менее реальные претензии к django-pingback у меня тоже есть. Хотя я сразу признаюсь, что не пробовал во что бы то ни стало с ней ужиться, просто код почитал. Претензии такие: Зависит от django-xmlrpc, хотя на мой взгляд XML-RPC в Питоне и так достаточно простая вещь, чтобы не городить для неё Джанго-специфичного слоя. Использование обобщённого XML-RPC-слоя тянет за собой необходимость делать в нём регистрацию pingback-хендлеров или регистрировать middleware, которая будет делать это за вас. В качестве цели пинга регистрируются объекты моделей, а не любой произвольный URL сервера. У приложения есть свои модели, и как я понимаю, пингбеки оно хранит как само хочет, а не так, как мне надо. Библиотека не ищет цитату из поста и автора так, как мне давно хотелось. Pingdjack Получилась библиотечка из двух модулей: клиента и сервера. Единственная внешняя зависимость — html5lib, без неё нынче никуда :-). Клиента я просто выдрал из Cicero. Он состоит из трёх функций: external_urls, которая ищет внешние ссылки в куске HTML'а ping, которая пингует один URL от имени другого ping_external_urls, которая соединяет одно с другим, пингуя все внешние ссылки из … -
Pingdjack
Понадобился мне недавно pingback-сервер, и я, посмотрев на django-pingback, в приступе NIH-синдрома написал своё приложение — pingdjack. За название спасибо Михаилу Лукьянченко. Отмазка Более-менее реальные претензии к django-pingback у меня тоже есть. Хотя я сразу признаюсь, что не пробовал во что бы то ни стало с ней ужиться, просто код почитал. Претензии такие: Зависит от django-xmlrpc, хотя на мой взгляд XML-RPC в Питоне и так достаточно простая вещь, чтобы не городить для неё Джанго-специфичного слоя. Использование обобщённого XML-RPC-слоя тянет за собой необходимость делать в нём регистрацию pingback-хендлеров или регистрировать middleware, которая будет делать это за вас. В качестве цели пинга регистрируются объекты моделей, а не любой произвольный URL сервера. У приложения есть свои модели, и как я понимаю, пингбеки оно хранит как само хочет, а не так, как мне надо. Библиотека не ищет цитату из поста и автора так, как мне давно хотелось. Pingdjack Получилась библиотечка из двух модулей: клиента и сервера. Единственная внешняя зависимость — html5lib, без неё нынче никуда :-). Клиента я просто выдрал из Cicero. Он состоит из трёх функций: external_urls, которая ищет внешние ссылки в куске HTML'а ping, которая пингует один URL от имени другого ping_external_urls, которая соединяет одно с другим, пингуя все внешние ссылки из … -
Receptes de South
Pels aquelles que encara no el coneixeu, permeteu-me que us presenti south una eina per a controlar els canvis que es van fent al model i poder-los aplicar a la nostra base de dades. South és una eina fantàstica, però no substitueix ni la necessitat de fer còpies de seguretat abans de fer algun canvi que pugui significar la destrucció o alteració de dades, ni la necessària coordinació entre els diferents membres de l'equip de desenvolupament. Al tutorial des south està molt bén explicat tot, així que aquest apunt miraré de posar les receptes que he trobat més interessants, bàsicament per a no oblidar-me'n. Canvi de nom d'un camp South intentarà esborrar el camp i crear-ne un de nou. No sap que el que volíeu era un canvi de nom així que: Fem la migració de la manera habitual python manage.py schemamigration app --auto South generarà una nova migració. Amb el vostre editor preferit, editau-la i eleminau les referències a l'eliminació i creació del camp. En el seu lloc, utilitzau directament l'API de South, per escriure db.rename_column(table_name, column_name, new_column_name) amb les columnes en sentit contrari per desfer la migració, obviament... Hem modificat un camp a la BD directament Les primeres … -
SM.Org software update 2012
Over the course of a few recent weeks I updated this site to a more modern software and revised some previously made choices. This one was loooong overdue considering that I still ran Ubuntu 9.10 before the update meaning that the system was almost 3 years old. Here are some mostly useless but probably fascinating notes about it. Core system upgrades Running a comparatively low-load site I had a luxury not to plan for complex procedures minimizing downtime. What I did was just SSHing on the host and running do-release-upgrade under "screen" five times in a row. Linode's upgrade docs were holding my hand during the process. Currently the site runs on Ubuntu 12.04 "Precise" and 3.0 Linux kernel. It's good to have modern packages! Notable moments (read: long downtimes) during the upgrades: Ubuntu's integrated mail stack was good back then and these days it's just wonderful! Upon installing a single package "mail-stack-delivery" you get yourself a completely set up mail server that can send mail, accept mail from outside and that provides an IMAP interface to your mailbox. It even does necessary SSL key generation magic for me, so I can do authorization from my mail client securely. What … -
SM.Org software update 2012
Over the course of a few recent weeks I updated this site to a more modern software and revised some previously made choices. This one was loooong overdue considering that I still ran Ubuntu 9.10 before the update meaning that the system was almost 3 years old. Here are some mostly useless but probably fascinating notes about it. Core system upgrades Running a comparatively low-load site I had a luxury not to plan for complex procedures minimizing downtime. What I did was just SSHing on the host and running do-release-upgrade under "screen" five times in a row. Linode's upgrade docs were holding my hand during the process. Currently the site runs on Ubuntu 12.04 "Precise" and 3.0 Linux kernel. It's good to have modern packages! Notable moments (read: long downtimes) during the upgrades: Ubuntu's integrated mail stack was good back then and these days it's just wonderful! Upon installing a single package "mail-stack-delivery" you get yourself a completely set up mail server that can send mail, accept mail from outside and that provides an IMAP interface to your mailbox. It even does necessary SSL key generation magic for me, so I can do authorization from my mail client securely. What … -
Weblog fixes
-
Git repository on your own server
-
Narrowing the Gender Gap in the Open Source community
Diversity is important in a workplace environment. Having different points of view from people with different life experiences brings creative new ideas and innovative solutions to the software development process. As a team of web developers that designs and builds custom web applications, creativity and gender diversity, I would argue, are closely tied and both ...