Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
One Change Is Not Enough
Sometimes just doing one major infrastructure move at once isn't quite enough to whet my appetite. Last week, me and the rest of the Lanyrd team pulled off two major infrastructure changes in two hours - see our blog post on the move for some background information as well as an overview of the timeline. I'd like to take a closer look at the technical details of this move and show how exactly we pulled off changing our hosting provider, database vendor and operating system version all in one go. Hosting For many startups, there comes a time when the switch to dedicated hardware and a more 'traditional' hosting model makes sense, and Lanyrd is one of those - we're fortunate to be at least partially a content-based site, and have two distinct advantages: Most traffic spikes are to one or two conference pages, and are an easily cacheable pattern. Conferences are planned well in advance, so we get good notification of when to expect high-traffic periods for more interactive use. This means that we're not subject to a huge amount of daily variation or unpredicted traffic spikes, and even if we get some, we have enough overhead to deal … -
Einladung zur Django-UserGroup Hamburg am 14. November
Das nächste Treffen der Django-UserGroup Hamburg findet am Mittwoch, den 14.11.2012 um 19:30 statt. Dieses Mal treffen wir uns in den Räumen der intosite GmbH im Poßmoorweg 1 (3.OG) in 22301 Hamburg. Da wir in den Räumlichkeiten einen Beamer zur Verfügung haben hat jeder Teilnehmer die Möglichkeit einen kurzen Vortrag (Format: Lightning Talks oder etwas länger) zu halten. Konkrete Vorträge ergeben sich erfahrungsgemäß vor Ort. Eingeladen ist wie immer jeder der Interesse hat sich mit anderen Djangonauten auszutauschen. Eine Anmeldung ist nicht erforderlich, hilft aber bei der Planung. Weitere Informationen über die UserGroup gibt auf unserer Webseite www.dughh.de. -
Django 1.5, Python 3.3, and Virtual Environments
Today I wanted to tinker around with the experimental support for Python 3 in Django 1.5 (alpha). -
Managing style sheets and JavaScript files with webassets
webassets is an application that manages (compress and join) static files like JavaScript or CSS (LESS, SASS too) files. It can work with various frameworks, including Django. Everything is described in the documentation. Compressed files have slightly smaller size and they load faster. One file made out of multiple CSS or JS files reduces the amount of HTTP requests needed to load the website. That also improves the load times. -
SendGrid Events and Eldarion Open Source
Yesterday, I blogged about one of our new open source Django apps, django-sendgrid-events. It's a small app, in terms of lines of code and/or complexity, but I think it opens up a ton of potential in things you can do for users of your site.In addition, to making that post yesterday, we updated our Open Source page with half dozen or so new Django apps that we have released throughout 2012.In addition, we have been gettings tons of great feedback from a post published about a month ago, entitled 5 Reasons to Hire an Agency. If you are in the position of looking to hire new engineers either as full time employees or as contractors then give this post a read first. If you have any questions at all I welcome the opportunity to speak with you on the phone, take your emails, or respond publicly to comments on this post.Go check these things out! I know you'll find more than a couple things useful if you are setting out to build a new site today, or even updating an old favorite. -
Django Extensions 1.0.1
Minor version update Django-Extensions 1.0.1 is out. This release fixes the following problems: spelling typo in README tests: shebang line in run_tests.py logging: Fix compatibility with python 2.6 media: Fix media directory in packaging admin extensions: Do not $ in javascript to avoid conflicts and redefines. -
How to create a virtual environment that also uses global modules
Last weekend I upgraded my Mac to Mountain Lion. I installed Python 2.7 with PIL and MySQLdb and virtualenv using MacPorts. When I created and activated a virtual environment with cd myproject virtualenv . . bin/activate the PIL and MySQLdb modules were unrecognizible in that environment. What I needed was just different Django versions in my virtual environments, but MySQLdb and PIL libraries had to be shared. After a quick search I found an additional parameter for the creation of virtual environment: virtualenv --system-site-packages . With this parameter I could use my global modules within the virtual environment. -
Not exactly, not exactly tim the enchanter
I've been putting off writing about my experience with django form wizard for some time now. I came across this blog post by Kenneth Love which finally compelled me to write this down. About Django Form Wizard: Form Wizard can be handy when you have a huge form, and you want to make it less intimidating to the user by splitting it into multiple steps. If you have glued multiple forms together with sessions or whatnot and it turned out to be a mess, you now what I'm talking about :) Think surveys, checkouts, lengthy registrations etc. The class WizardView implements most of functionality while subclasses SessionWizardView, CookieWizardView etc. specify which backend to use. Typically, the view takes a list of forms and presents them one by one. After each step, the form is validated and the raw form data is saved in the backend (session or cookie for POST data and file_storage for files). After the last step, each form is filled with raw data from the backend and validated again. The list of fully-filled up form instances is then passed to the done handler where the forms can be processed. I guess the key bit of info here … -
Django Beginner Series - Introduction
Some Twitter followers could already know that I am working on a book. Just not what it is about. Big announcement: It will be about web application development using Django. It is supposed to be an easy entry in the world of Django and tries to cover as much as possible in a simple way to get started with the framework. If you do not care why I am doing this skip to "ideas and how this blog is involved" to get an idea what tutorials I will post in the course of the next weeks. Django is the best documented project I know. You can find nearly anything in the documentation and if you are not comfortable browsing it you can just read the code with comments. But there is something Django lacks. I know that not everyone agrees with me on this. But I also know how many people asked me basic things they could not figure out just from reading the tutorial. Django needs some basic introduction material. I do not think it would be wise to rewrite the whole documentation. If I want to know something about a model field, how a battery works or just … -
Not Exactly Tim the Enchanter
Django has always been hailed as having great, awesome documentation. And, for the most part, this distinction has been deserved. But every once in a while, you find an area that's just...lacking. An area that you know exists but you've never gone into because it didn't come up and no one else used it but then you finally got a reason to use it...and then you find out it's so lacking in documentation that you have to dive into the source code. This is one of those areas. Welcome to Django Form Wizard. What is Django Form Wizard? At it's most basic, Django's Form Wizard (DFW from now on, OK?) is a way to auto-generate a set of views w/ a single form in each view. Most of the time it uses one template but you can have a different template for each view. Most wizards have numbered steps but you can have named ones if you want. Also, most wizards deal with standard forms (highly recommended) but can, of course, use formsets and model forms. You've all used wizards before, I'm sure. A set of forms that you fill out in order and, at the end, something larger is … -
Introduction to Django Selenium Testing
If you’ve never heard of Selenium, put simply, it’s a tool that allows you to create tests that are run in the browser and interact with your UI in the same way as if you were manually testing your website or app. It’s the de-facto standard to test complex Web UI interactions that usually involve a heavy use of JavaScript, and that’s probably the main use-case for it. Other than that, we also use it sometimes as a helper tool for cross-browser design (CSS) testing by running Selenium tests through different browsers and taking screenshots or recording videos. Selenium’s been around for a long time now, and is available in various programming languages, but up until Django 1.4 came along you couldn’t have your Selenium tests (easily) integrated with your Django test suite. Since then, a new class named LiveServerTestCase, that your Selenium test classes can inherit from, was introduced. This class will automatically run a test server in the background and your Selenium tests will be run against that server. It not only simplifies the process, but it also means your tests can be setup the same way your Django tests are, and so both can be run together … -
Introduction to Django Selenium Testing
If you’ve never heard of Selenium, put simply, it’s a tool that allows you to create tests that are run in the browser and interact with your UI in the same way as if you were manually testing your website or app. It’s the de-facto standard to test complex Web UI interactions that usually involve a heavy use of JavaScript, and that’s probably the main use-case for it. Other than that, we also use it sometimes as a helper tool for cross-browser design (CSS) testing by running Selenium tests through different browsers and taking screenshots or recording videos. Selenium’s been around for a long time now, and is available in various programming languages, but up until Django 1.4 came along you couldn’t have your Selenium tests (easily) integrated with your Django test suite. Since then, a new class named LiveServerTestCase, that your Selenium test classes can inherit from, was introduced. This class will automatically run a test server in the background and your Selenium tests will be run against that server. It not only simplifies the process, but it also means your tests can be setup the same way your Django tests are, and so both can be run together … -
The missing documentation for django.utils.datastructures
Note django.utils.datastructures is intentionally not documented by the django core devs because it is an internal API and is liable to change without any notice. This file is not governed by django's lenient backwards-compatible policy. You have been sufficiently warned! With the note out of the way, let's look at the interesting datastructures in this file. You may ask why we should learn about those when we shouldn't be using them? Reading code is the best way of learning and this file has some beautiful code. MergeDict is the first of the datastructures in the file. It provides a dictionary like interface but can look up from multiple dictionaries provided during the initialization. Here's an example: >>> md = MergeDict({"foo": "bar", "moo": "cow"}, {"abc": "def"}) >>> md["foo"] 'bar' >>> md["abc"] 'def' >>> md.get("abc") 'def' >>> md["xyz"] KeyError: >>> md.items() [('foo', 'bar'), ('moo', 'cow'), ('abc', 'def')] >>> md.keys() ['foo', 'moo', 'abc'] >>> md.values() ['bar', 'cow', 'def'] The MergeDict is used within django in attaching values with a form widget and in request.REQUEST. The built-in dictionary does not maintain the order of the items but the SortedDict is a subclass of the built-in dictionary that maintains the keys in exactly the same … -
django-scribbler, a lightweight front-end interface for Django template editing
django-scribbler is a new open-source project published by the team at Caktus. Its goal is to create a seamless way for authorized end users to make edits to specific blocks of content in their Django template. The original project idea came from a conversation Mark and I had about a front end editor Mark was working on. His original idea included a toggled area on the page where users could preview the changes to the content. I suggested it would be even better by showing the user their changes as they were making them. That inspiration came from Bret Victor's talk on “Inventing on Principle”. In his talk, he explains that creators need and “immediate connection to what they create.” To create this effect of seeing your edits as they happen, the developer defines blocks in the template that can be edited by the end user on the front end. Once logged in, that user is able to hover over those blocks and edit as they see fit. The user immediately can see their changes. When they are ready, they can save changes to the database or even save as a draft. During Caktus's Inaugural ShipIt Day, Mark and I … -
My vagrant setup on OSX
I said in using vagrant for developing on OSX: why? that I chose vagrant for setting up my development environment. Now it's time for some specifics. Vagrant box setup and location Per virtual machine, vagrant uses a directory with a Vagrantfile in it. As a convention, I place my vagrant directories as subdirectory inside ~/vm/. The name of the subdirectory (I'll use "django" as an example in this blog post) is the name I use for the virtual machine. So ~/vm/django/Vagrantfile is the vagrant file for my "django" virtual machine. I have one other ("barebones"), but I already know I'm also going to make a "php" one for three mysql/php sites that I sometimes do a bit of work on. Those end up in ~/vm/php/ and so. Everything that's not in git (/svn/hg/bzr) doesn't exist, so I've versioned my ~/vm/ directory. I ignore (.gitignore) the django/php/barebones directories. The Vagrantfiles in those directories are symlinks to ~/vm/vagrantfile_django and so on. There's a README.txt to help me set it all up when I move to a new computer. I also have a fabfile for setting up the (django) box automatically. Some of the things the fabfile does: Install a couple of extra … -
Evennia changes to BSD license
As of today, Evennia changes to use the very permissive BSD license. Now, our previous "Artistic License" was also very friendly. One main feature was that it made sure that changes people made to the core Evennia library (i.e. not the game-specific files) were also made available for possible inclusion upstream. A good notion perhaps, but the licensing text was also quite long and it was clear some newcomers parsed it as more restrictive than it actually was.... And let's be honest, it's not like I would have come hunting down anyone not complying fully with the Artistic license's terms. Changing to the much simpler and more well-known BSD license better clarifies the actual licensing situation.After all, far too many older MUD-code bases are weighted by a legacy of licensing issues. Anything we can do to avoid this is better in the long run. Indeed we hope this change in licensing will remove eventual licensing doubts for new adopters and have more people join and contribute to the project. -
Mercurial Mirror For Django 1.5 branch
Django has just released the first alpha for the next big release, 1.5. As such they created the 1.5.x branch that will lead to the 1.5.0 release and then will become the stable branch. I do not intend to use the 1.5 branch before the final release, but I’ve already setup the mirror nonetheless. The mirror […] -
Easily Add Stripe Payments to your Django Site
Earlier today I blogged over on Eldarion's site about how you can easily add Stripe payments to your website with a new app that we have developed and open-sourced under the BSD license.Be sure to check it out! -
Django Extensions 1.0.0
So it finally happened, Django-Extensions 1.0 is out. After getting a lot of feedback from the community, I decided to call it 1.0. Discussions about going fully on-par with Django on version numbering was very interesting and the nice thing about a 1.0 release is that we can always do that later. For now having 1.0 is good enough and besides if we would have called it 1.4 now we never would have been able to celebrate the 1.0 release ;) Please all start testing this release so we can iron out any small issues left as soon as possible. Some highlights of the changes in this release are: new validate_templates, Checks templates for errors. sqldiff: PostgreSQL HStore support runserver_plus: Django 1.4 WSGI_APPLICATION support runserver_plus: add --print-sql option dumpscript; several improvements shell_plus: added support for ipython notebook shell_plus: added --print-sql option mail_debug: several improvments Using Travis-CI now in combination with GitHub Several fixed for Django 1.4 -
Simple Site Checker and the User-Agent header
Preface: Nine months ago(I can’t believe it was that long) I created a script called Simple Site Checker to ease the check of sitemaps for broken links. The script code if publicly available at Github. Yesterday(now when I finally found time to finish this post it must be “A few weeks ago”) I decided to run it again on this website and nothing happened – no errors, no warning, nothing. Setting the output level to DEBUG showed the following message “Loading sitemap …” and exited. Here the fault was mine, I have missed a corner case in the error catching mechanism i.e. when the sitemap URL returns something different from “200 OK” or “500 internal server error”. Just a few second and the mistake was fix. Problem and Solution: I ran the script again and what a surprise the sitemap URL was returning “403 Forbidden”. At the same time the sitemap was perfectly accessible via my browser. After some thinking I remembered about that some security plugins block the access to the website if there is not User-Agent header supplied. The reason for this is to block the access of simple script. In my case even an empty User-Agent did … -
Marcus: двуязычный блог
Ещё в январе я тихо заменил здесь WordPress на самописный блог. Публично это отразилось разве что в двух твитах, и никакого поста я про это не написал. Отчасти из-за лени, отчасти от того, что всё там было довольно банально. Один из плюсов собственного блогософта в том, что к нему можно прикручивать новые фичи именно в таком виде, в котором хочется. И после реализации в блоге двуязычности, я посчитал, что стоит сделать небольшой технический обзор. Сразу скажу, что я не планировал блог, как коробочное приложение. И хотя написан он в автономном стиле, он, всё же, достаточно своеобразен и вряд ли подойдёт по фичам большинству блогеров. Код Код можно смотреть в бранче на Launchpad'е. Его получилось немного — около 860 строк, и он, как по мне, хорошо читается. Интересно, что примерно 250 строк из всех ушло как раз на двуязычность. Впрочем, строчек непосредственно в коде блога получилось так немного, потому что много чего вынесено в библиотеки: pingdjack используется для рассылки и приёма pingback'ов scipio с его антиспам-конвейером заведует авторизацией по OpenID в комментариях subhub реализует персональный PSHB-хаб, благодаря чему посты мгновенно появляются в яндексовом Поиске по блогам и, следовательно, Подписках — новом воплощении старой Я.Ленты. Фичи Ничего экстраординарного блог собой не представляет. … -
Marcus: двуязычный блог
Ещё в январе я тихо заменил здесь WordPress на самописный блог. Публично это отразилось разве что в двух твитах, и никакого поста я про это не написал. Отчасти из-за лени, отчасти от того, что всё там было довольно банально. Один из плюсов собственного блогософта в том, что к нему можно прикручивать новые фичи именно в таком виде, в котором хочется. И после реализации в блоге двуязычности, я посчитал, что стоит сделать небольшой технический обзор. Сразу скажу, что я не планировал блог, как коробочное приложение. И хотя написан он в автономном стиле, он, всё же, достаточно своеобразен и вряд ли подойдёт по фичам большинству блогеров. Код Код можно смотреть в бранче на Launchpad'е. Его получилось немного — около 860 строк, и он, как по мне, хорошо читается. Интересно, что примерно 250 строк из всех ушло как раз на двуязычность. Впрочем, строчек непосредственно в коде блога получилось так немного, потому что много чего вынесено в библиотеки: pingdjack используется для рассылки и приёма pingback'ов scipio с его антиспам-конвейером заведует авторизацией по OpenID в комментариях subhub реализует персональный PSHB-хаб, благодаря чему посты мгновенно появляются в яндексовом Поиске по блогам и, следовательно, Подписках — новом воплощении старой Я.Ленты. Фичи Ничего экстраординарного блог собой не представляет. … -
JQuery Sortables + AJAX + Django = fun
Like my other code posts, this one starts with a problem (or an opportunity). How do I integrate jQuery Sortable with Django? The use case was designing a slideshow and I wanted users to be able to sort slides and pull them from the "active" column to the "inactive" column. Heck, While we're at it, how about being able to drag to a trashcan? Honestly, I'm not the greatest with javascript. But I'm persistent. If you haven't tried it, jsFiddle is an awesome workspace for developing javascript code. You can quickly make changes and see what happens in seconds. For those of you who are impatient and don't want to scroll to the example at the bottom, here is my fiddle for this code. Here's the general game plan for accomplishing this. I'm going to let the code speak for itself for the details, it should be pretty straightforward to read. create 3 separate lists: active, inactive, trash use a common class for slides pass the PK of the slide in the 'id' attribute make each list sortable and connect them to each other in the 'update' event, send the (active|inactive|trash) PKs via POST to the server in the 'receive' … -
Django GetOrCreateView
Today I decided to use the Django class based view (CBV) CreateView, but I wanted to avoid duplications and submit to the view from the front page of a site. The reason was I needed a simple newsletter signup form. This is what I cooked up and should work for Django 1.3, 1.4, and the forthcoming 1.5 release. Here is what I did: 1. Installed dependencies This version requires the following package to be pip installed into your virtualenv. django-extensions so we can have easy timestamps on models. This also needs to be added to your list of INSTALLED_APPS: INSTALLED_APPS += ( 'django_extensions', ) 2. Defined the model The model is really simple, and inherits from TimeStampedModel so we know when people signed up: from django.db import models from django_extensions.db.models import TimeStampedModel class NewsLetterSignup(TimeStampedModel): email = models.EmailField("Email") def __unicode__(self): return self.email 3. Wrote the view Here's the somewhat challenging part that forced me to dive into Django's source code. Even with the documentation work we've done over the past few months, it's clear we've got a long way to go. Because of that source code diving, for this blog post I really did my best to document why I did … -
Django GetOrCreateView
Today I decided to use the Django class based view (CBV) CreateView, but I wanted to avoid duplications and submit to the view from the front page of a site. The reason was I needed a simple newsletter signup form. This is what I cooked up and should work for Django 1.3, 1.4, and the forthcoming 1.5 release. Here is what I did: 1. Installed dependencies This version requires the following package to be pip installed into your virtualenv. django-extensions so we can have easy timestamps on models. This also needs to be added to your list of INSTALLED_APPS: INSTALLED_APPS += ( 'django_extensions', ) 2. Defined the model The model is really simple, and inherits from TimeStampedModel so we know when people signed up: from django.db import models from django_extensions.db.models import TimeStampedModel class NewsLetterSignup(TimeStampedModel): email = models.EmailField("Email") def __unicode__(self): return self.email 3. Wrote the view Here's the somewhat challenging part that forced me to dive into Django's source code. Even with the documentation work we've done over the past few months, it's clear we've got a long way to go. Because of that source code diving, for this blog post I really did my best to document why I did …