Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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 ... -
I don't belive in software complexity
Ok, building software could be complex, but it doesn't have to. Recently I read this quote Complexity happens when you don't understand a problem fully It's true. We, the software craftsmen, have a very difficult task upon us: building tools for proposes we don't understand fully. I got it screeching my fingers with a bit of bioinformatics. In finance is no different. Today I saw poor JMS -
Four Libs Good, Two Libs Better
Our approach to site construction used to favor collecting open source apps and gluing them together in order to build up scaffolding quickly and to reuse the efforts of others. This is still a prominent part of how we operate, but we also don’t automatically reach for an app just because one exists — even ones we know are high quality. -
Four Libs Good, Two Libs Better
Click here to see this post in it's natural habitat and to watch and leave comments. [with apologies to Mr. Orwell] I’ve noticed a subtle shift in how we approach building up new sites over the last couple of years. Our approach to site construction used to favor collecting open source apps and gluing them together in order to build up scaffolding quickly and to reuse the efforts of others. This is still a prominent part of how we operate, but we also don’t automatically reach for an app just because one exists—even ones we know are high quality. In the past, pip requirements with dozens of dependencies was common for larger sites. These days we tend to use a lot more discretion before adding an entry to those files. While reusable apps can seem to offer productivity gains by providing the base for a feature with minimal effort, there can be a lot of hidden time costs that only surface intermittently throughout the life of a project (often at inconvenient times). Apps pull in their own dependencies, which you then need to manage. Some parts of the app provide exactly what you need, while others can be problematic. You’re … -
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 … -
Auto-building Sphinx docs
Here’s a quick way to automatically regenerate your Sphinx docs as you make changes to the source. There’s probably a million ways to do this; here’s mine: $ pip install watchdog $ watchmedo shell-command \ --patterns="*.txt" \ --ignore-pattern='_build/*' \ --recursive \ --command='make html' -
Django book: abort abort abort
-
Django Class Based View: email form with CAPTCHA
Yesterday I showed how to implement a simple email form for Django using Class Based Views. Today I'm going to extend yesterday's work to use the excellent RECAPTCHA service to help reduce spam content. This version requires pip installing the following into your virtualenv. pip install django-crispy-forms so we can do Python driven layouts. pip install django-floppyforms so we get HTML5 elements for free. pip install django-recaptcha to do the RECAPTCHA work. Don't forget to add the app to your INSTALLED_APPS in settings.py: INSTALLED_APPS += ( 'crispy_forms', 'floppyforms', 'captcha', ) Generate your KEYs from the RECAPTCHA site and add them in settings.py: RECAPTCHA_PUBLIC_KEY = '6LcVu9ESAAAAANVWwbM5-PLuLES94GQ2bIYmSNTG' RECAPTCHA_PRIVATE_KEY = '6LcVu9ESAAAAAGxz7aEIACWRa3CVnXN3mFd-cajP' In myapp.forms.py: from captcha.fields import ReCaptchaField # Only import different from yesterday from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import floppyforms as forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) captcha = ReCaptchaField() # Only field different from yesterday def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(ContactForm, self).__init__(*args, **kwargs) In myapp.views.py: # Unchanged from yesterday. :-) from django.conf import settings from django.core.mail import send_mail from django.views.generic import FormView from myapp.forms import ContactForm class ContactFormView(FormView): form_class = ContactForm template_name = "myapp/email_form.html" success_url = … -
Django Class Based View: email form with CAPTCHA
Yesterday I showed how to implement a simple email form for Django using Class Based Views. Today I'm going to extend yesterday's work to use the excellent RECAPTCHA service to help reduce spam content. This version requires pip installing the following into your virtualenv. pip install django-crispy-forms so we can do Python driven layouts. pip install django-floppyforms so we get HTML5 elements for free. pip install django-recaptcha to do the RECAPTCHA work. Don't forget to add the app to your INSTALLED_APPS in settings.py: INSTALLED_APPS += ( 'crispy_forms', 'floppyforms', 'captcha', ) Generate your KEYs from the RECAPTCHA site and add them in settings.py: RECAPTCHA_PUBLIC_KEY = '6LcVu9ESAAAAANVWwbM5-PLuLES94GQ2bIYmSNTG' RECAPTCHA_PRIVATE_KEY = '6LcVu9ESAAAAAGxz7aEIACWRa3CVnXN3mFd-cajP' In myapp.forms.py: from captcha.fields import ReCaptchaField # Only import different from yesterday from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import floppyforms as forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) captcha = ReCaptchaField() # Only field different from yesterday def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(ContactForm, self).__init__(*args, **kwargs) In myapp.views.py: # Unchanged from yesterday. :-) from django.conf import settings from django.core.mail import send_mail from django.views.generic import FormView from myapp.forms import ContactForm class ContactFormView(FormView): form_class = ContactForm template_name = "myapp/email_form.html" success_url = … -
Django Unchained
As you have hopefully already noticed, our website works very nicely on mobile devices. However since many of you will be visiting Switzerland from abroad, you might not have an (affordable) data connection on those devices when you're at the conference.That's why I'm very happy to announce the guys at exopoint have very kindly made all the information you need for DjangoCon Europe 2012 available offline using their app. If you have an iPhone, an Android Phone or a Windows Phone, head over to their website using your mobile device phone to install the app. Once you've done that, open the link again to add DjangoCon Europe to the app.Should that not work for you, just search the app market/store of your phone for the "exopoint" app and install it. After the installation, tap the "+" icon in the app and search for "Djangocon".If you want to fully unchain your phone for DjangoCon and get a local SIM card, we have put up a summary of your options on our newest information page about Zurich. -
Simple Django email form using CBV
Here's a simple FormView Class Based Views for Django. Here is a sample of how to do one as a simple email form. There is no CAPTCHA in this example, that's the topic of a future blog post. This version requires the following packages pip installed into your virtualenv. django-crispy-forms so we can do Python driven layouts. django-floppyforms so we get HTML5 elements for free. They also need to be added to your list of INSTALLED_APPS: INSTALLED_APPS += ( 'crispy_forms', 'floppyforms', ) In myapp.forms.py: from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import floppyforms as forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(ContactForm, self).__init__(*args, **kwargs) In myapp.views.py: from django.conf import settings from django.core.mail import send_mail from django.views.generic import FormView from myapp.forms import ContactForm class ContactFormView(FormView): form_class = ContactForm template_name = "myapp/email_form.html" success_url = '/email-sent/' def form_valid(self, form): message = "{name} / {email} said: ".format( name=form.cleaned_data.get('name'), email=form.cleaned_data.get('email')) message += "\n\n{0}".format(form.cleaned_data.get('message')) send_mail( subject=form.cleaned_data.get('subject').strip(), message=message, from_email='contact-form@myapp.com', recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS], ) return super(ContactFormView, self).form_valid(form) In templates/myapp/email_form.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Send an email{% endblock %} {% block content %} <div class="row"> <div … -
Simple Django email form using CBV
Here's a simple FormView Class Based Views for Django. Here is a sample of how to do one as a simple email form. There is no CAPTCHA in this example, that's the topic of a future blog post. This version requires the following packages pip installed into your virtualenv. django-crispy-forms so we can do Python driven layouts. django-floppyforms so we get HTML5 elements for free. They also need to be added to your list of INSTALLED_APPS: INSTALLED_APPS += ( 'crispy_forms', 'floppyforms', ) In myapp.forms.py: from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import floppyforms as forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(ContactForm, self).__init__(*args, **kwargs) In myapp.views.py: from django.conf import settings from django.core.mail import send_mail from django.views.generic import FormView from myapp.forms import ContactForm class ContactFormView(FormView): form_class = ContactForm template_name = "myapp/email_form.html" success_url = '/email-sent/' def form_valid(self, form): message = "{name} / {email} said: ".format( name=form.cleaned_data.get('name'), email=form.cleaned_data.get('email')) message += "\n\n{0}".format(form.cleaned_data.get('message')) send_mail( subject=form.cleaned_data.get('subject').strip(), message=message, from_email='contact-form@myapp.com', recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS], ) return super(ContactFormView, self).form_valid(form) In templates/myapp/email_form.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Send an email{% endblock %} {% block content %} <div class="row"> <div … -
Compiling Dust.js templates with django-mediagenerator
Compiling Dust.js templates with django-mediagenerator Here at 2General we’ve used django-mediagenerator as the asset manager in many of our latest projects. It combines the best parts of Django’s own staticfiles implementation and the older django-compressor app. Dust.js is a fast, asynchronous JavaScript-based templating engine which runs both in browsers and on Node.js. We haven’t used Dust.js extensively yet, but we immediately noticed that if we’re planning to use it, we need to compile Dust.js templates during our normal build process, i.e. be able to add them in our mediagenerator bundles. Jump to code example » Use our improved django-mediagenerator fork Unfortunately django-mediagenerator project is somewhat abandoned as its original authors decided to call it quits last year. However, there’s an “official” Github fork which hasn’t received any updates yet and our own fork which we have updated with these improvements: Improved performance of the development mode (MEDIA_DEV_MODE=True) through caching Support for compiling Dust.js templates in JavaScript bundles Django-mediagenerator assets (usually JavaScript files and stylesheets) are organized into “bundles” in your settings.py. On a production server all the files in a bundle are served as one concatenated and minified file. The created files are versioned with a hash, so django-mediagenerator also … -
How to install Node.js packages and Ruby gems in virtualenv
How to install Node.js packages and Ruby gems in virtualenv Virtualenv is a superb tool for creating isolated environments for development with Python. However, if your project requires libraries in other languages, you may want to install them in your virtual environment as well. Here’s how to do it with Node.js packages and Ruby gems. If you’re using virtualenvwrapper (and you should), you can put this in your postactivate script. Otherwise make sure some other way that these variables are set: # node.js packages export npm_config_prefix=$VIRTUAL_ENV # ruby gems export GEM_HOME=$VIRTUAL_ENV export GEM_PATH="" Installing Node.js packages As an example, to install the Less CSS compiler in the virtual environment, use: $ npm install -g less (Note the -g option!) The lessc script will be conveniently symlinked into $VIRTUAL_ENV/bin: $ echo "div { a { color: #f00; } }" > my.less $ lessc my.less div a { color: #f00; } The virtualenv trick requires a fairly recent version of Node.js. If you’re on an Ubuntu box, the easiest way to get one is the following (tested on 11.10 and 12.04): $ sudo add-apt-repository ppa:chris-lea/node.js $ sudo apt-get update $ sudo apt-get install -y npm Installing Ruby gems Ruby gems are installed … -
Django Job – Worcestershire, United Kingdom
My company is hiring. Details here. -
May 12th, 2012 LA Open Source Recap
On May 12th, 2012, over 50 Python, C++, Ruby, PHP, JavaScript, and Node.js developers arrived to code on a variety of projects. It was awesome! Tons of open source projects saw contributions, and people across languages and frameworks worked together. Event Background Less then two weeks before May 12, a bunch of us Los Angeles area Python developers were hanging out and wishing we had a local sprint to attend that was just about developers working on open source projects. It was then that Audrey Roy and I, along with an army of hardworking volunteers, decided to stop wishing and make it happen on May 12th. We lined up a venue, contacted awesome sponsors Spire.io, Heroku, Github, Cars.com, and Cartwheel Academy. As we did that, we also invited people from the many Los Angeles programming communities in Los Angeles to join us. The result of everyone's hard work? We filled up all sixty spots in less than 96 hours! Some of the projects worked on included: Salt Stack: https://github.com/saltstack/salt A node.js-powered streaming terminal, allowing for shared input at a terminal among several participants. A JavaScript powered astrolabe. Settlers of Catan analytics in JavaScript. OpenFrameworks, a cross-platform toolkit for creative coding …