Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django's dictsort template tag
dictsort [1] Takes a list of dictionaries and returns that list sorted by the key given in the argument. Eg: {{ value|dictsort:"name" }} The documentation would let you to believe you can only sort dicts with it. What to do if you have a list of strings ? After a bit of fumbling around it turns out that dictsort doesn't do a mere __getitem__ on each object but instead will take each object as a template context and evaluate the key as a variable, like {{ name }} would. What does this mean ? It means you can sort a list of strings by using the least changing method as the sort attribute. Remember that django automatically calls any functions in templates. Example: >>> from django.template import Template, Context >>> print Template("""{% for i in items|dictsort:"lstrip" %} ... {{ i }} ... {% endfor %}""").render(Context({ ... 'items': ["x", "a", "c", "b"] ... })) a b c x Ofcourse, this won't work very well if your strings start with spaces. What else can you do? You can get in depth: >>> print Template("""{% for i in items|dictsort:"a.b.c.d" %} ... {{ i|safe }} ... {% endfor %}""").render(Context({ ... 'items': [ ... {'a': … -
Django's dictsort template tag
dictsort [1] Takes a list of dictionaries and returns that list sorted by the key given in the argument. Eg: {{ value|dictsort:"name" }} The documentation would let you to believe you can only sort dicts with it. What to do if you have a list of strings ? After a bit of fumbling around it turns out that dictsort doesn't do a mere __getitem__ on each object but instead will take each object as a template context and evaluate the key as a variable, like {{ name }} would. What does this mean ? It means you can sort a list of strings by using the least changing method as the sort attribute. Remember that Django automatically calls any functions in templates. Example: >>> from django.template import Template, Context >>> print Template("""{% for i in items|dictsort:"lstrip" %} ... {{ i }} ... {% endfor %}""").render(Context({ ... 'items': ["x", "a", "c", "b"] ... })) a b c x Of-course, this won't work very well if your strings start with spaces. What else can you do? You can get in depth: >>> print Template("""{% for i in items|dictsort:"a.b.c.d" %} ... {{ i|safe }} ... {% endfor %}""").render(Context({ ... 'items': [ ... {'a': … -
Flat as a Pancake
A week on a remote island leads to a lot of squashed things. I'm not entirely sure if they're related. After a wonderful relaxing week at /dev/fort on the Isle of Eigg - somewhere I can heartily recommend if you're after amazing landscapes in remote places - work continues on migrations, in amongst the preparations for my move to the US. The last two weeks has been entirely focused on migration squashing - the ability to take an existing set of migrations, replace them with just one migration, and then have all new installations use that one migration instead of taking minutes running all the small migrations you committed that evening when you just felt like adding some random new columns. But how? The way this is done is reasonably simple - we simply take the existing migrations, extract all of their operations, and concatenate them into one big list. This is, clearly, going to do the same thing as all the smaller migrations, and it's quite nice not having a hundred names flying past you when you first run migrate. It's still almost as slow, though; behind the scenes you're still issuing loads of ALTER TABLE commands on brand-new … -
Releasing BoutiqueHotel.me
Last week, me and Ted Valentin released our new website, BoutiqueHotel.me. Boutique hotels are, for those who don't know, (usually quite small) hotels with thought-through concepts and unique attributes. You can for example check out boutique hotels in Stockholm or gothenburg boutique hotels. The site's tech stack is Python + Django & Celery, PostgreSQL with PostGIS as database, memcached for caching and Redis as Celery's backend/broker. All maps on the website are powered by wonderful Leaflet. Hopefully, I will be be open sourcing some of the website's code through some JS/Python libs. For example our image viewer which calculates how to distribute the images to create a perfectly balanced photo album. I've realised that there are a lot of really nice hotels, and my current favorite is probably Treehotel in Harads quite far up north in Sweden. Our aim with this site is to have the largest collection of the world's boutique hotels, and to give a far better experience when searching for boutique hotels than any other site out there. For this reason, we've started with just releasing the site for Sweden, and Swedish boutique hotels, but in the upcoming weeks we will roll out more countries. -
Django Extensions 1.2.5
Django-Extensions version 1.2.5 is as a bug fix release for 1.2.4. Fixes two bugs in admin extensions: Fix autocomplete image pixel Fix ForeignKeySearchInput Javascript -
A list of Evennia topics
Some Evennia updates. Development Lots of work has been happening in the dev-clone of Evennia over the last few months.As alluded to in the last blog, the main work has been to move Evennia's webserver component into the Server-half of Evennia for various reasons, the most obvious one to make sure that all database writes happen in the same process, avoiding race conditions. But this move lead to a rework of the cache system, which in turn lead to me having to finalize the plans for how Out-of-Band protocols should be implemented server-side. And once that was finalized, OOB was pretty much implemented anyway. As part of making sure OOB trackers were updated correctly at all times meant reworking some of the ways data is stored ... So one thing led to another making this a bigger update than originally planned.I plan to make a more detailed post to the mailing list soon with more technical details of the (relatively minor) API changes existing users should expect. The merging of the clone into the main repo is still a little way off, but adventurous users have already started testing things.Google CodeI like Google Code. It's easy to manage and maintain, … -
Minify Django
Minify Django -
Skinny Django
Skinny Django -
Quick and handy wheel package format for Python applications
Python packaging needs some help. A solution to at least some problems may be wheel - a new format for fast and efficient software installation and distribution. It's described in few PEPs and now it's starting to take shape. It was showcased recently on PyCon PL 2013. There is nearly no wheels on pypi but we can use them locally to make local installations faster (handy for continuous integration systems and alike that build a project from scratch often). -
IP Street is looking to hire a Senior Developer! (Seattle)
If you know someone who fits the bill, send them this post! ———————————— Title: Senior Developer Reports to: VP Engineering About IP Street Founded in 2009, IP Street develops and markets software to help corporations, law firms, and financial analysts better analyze patent-related information. We make IP data easy to get, use, and understand! Summary We’re a start-up that’s developed a new way to visualize and data-mine intellectual property. We’re small and scrappy, have an innovative engineering team, and have built the business on awesome products that companies buy! Our technology stack is almost all open-source, with some nifty esoteric search technologies. Most of your work will be in Python and Django, in a Mac-based development environment, deploying to Linux. Other technologies include Celery, Postgres, Redis, and Solr. Our client-side code relies on Highcharts and Backbone, and supports desktop and mobile users. This is “small b” big data, with lots of interesting challenges! Responsibilities Collaborate with others in product direction, priorities, and features Design, implement, and test new product (primarily but not exclusively server-side) features Some front-end coding and debugging, as needed Make the user experience as powerful, simple, and manifest as possible Be positive, flexible, and do what’s needed … -
Flamewars as a Service
Our guest this week isBuddy Lindsey, host ofGoDjangovideos, works atConsumerAffairs.com.00:00:00.000 Intro00:05:45.000 Kiwi PyCon Videos00:07:00.000 Hardware is Hot00:12:43.000 Humans vs. Zombies00:15:15.000 django-easy-timezones00:20:00.000 Deploy Django00:24:46.000 pyenv00:29:30.000 Heroku Websockets00:33:56.000 Your own mini-Heroku00:37:40.000 Github tmux status00:40:18.000 Most Liked and Disliked Programming Languages -
Django Extensions 1.2.4
Django-Extensions version 1.2.4 got released as a bug fix release for 1.2.3. Turns out I made a small packaging mistake and the new templates for graph_models where not included in the release. -
Build a scalable feed using Stream-Framework and Django
It’s been a year since the original version of this blogpost was written and it’s time for an update. The Stream-Framework is currently the largest open source solution for building newsfeed. This post will point you in the right direction if you want to build a newsfeed using Stream-Framework and Django. We’ll be building an example app like this Pinterest style demo. Besides the open source Stream Framework we also offer a hosted solution for building newsfeed applications at getstream.io. The example application code for the hosted version can be found on Github. For the open source framework the example app code can be found here. Share and Enjoy: -
Django Extensions 1.2.3
Django-Extensions version 1.2.3 is out :) Bringing the usual bug fixes, improvements, etc. Special this time is that a bunch of extensions that had not seen changes in a long time got some new love. A special thanks for the contributions to SQLDiff and graph_models this time around. A new version of SYNC_MEDIA_S3 was also merged, now simply called sync_s3. The old version sync_media_s3 still exists but will be deleted around march 2014. Please give the new version a try if your using this ! :) ChangeLog: sqldiff support for doing diffs involving many-to-many relations sqldiff support finding missing foreignkey relations sqldiff now supports Table Inheritance graph_models now supports both pygraphviz and pydot graph_models refactored use of django templates so it's easier to change and extend graph_models sort items and make sure primary_key and foreignkeys are always on top graph_models (hopefully) make database relations (primary key and foreignkey) more clear graph_models do not hide foreign keys from attribute list (added option for if you want to hide this) graph_models allow to specify default values in settings file for graph_models command graph_models show inheritance arrows per default shell_plus Added SHELL_PLUS_PRE_IMPORTS and SHELL_PLUS_POST_IMPORTS which allow for including additional import directives before the … -
Django – Muito além do básico
Estou na Latinoware e acabei de apresentar uma parte da palestra “Django – Muito além do básico”. Sala lotada, público interessado, mas infelizmente houve um incidente nos encaminhamentos finais da palestra: acabou a luz! Sim, estou dentro da usina de Itaipu e o bloco em que estávamos ficou todo no escuro! Vou tentar ver com a organização se consigo um repeteco dessa palestra. Mas deixo aqui os slides que foram apresentados e fico à disposição para tirar qualquer dúvida. Obrigado a todos os participantes! Django – Muito além do básico from Christiano Anderson O post Django – Muito além do básico apareceu primeiro em Christiano Anderson. -
django-nbskel
Well it was time already to give some more code into the public domain and the community, so I decided to release my personal way of starting new django projects. I call it django-nbskel ("nb" for nomadblue and "skel" for skeleton). Development code can be found, along with my other apps, in Bitbucket: http://bitbucket.org/nabucosound/django-nbskel/ The project page is here. The purpose if this application is to contain a basic django project and help you out configure it to speed up the process of starting up a new development, be it a quick hack or a long project. I often need to produce new django projects and I don't enjoy doing repetitive things. They start basically with the same structure so with this app I can wrap all the first steps into a couple of actions. It also makes me feel secure because I always tend to forget to initialize settings, include files, import modules, and so on, so with django-nbskel I am sure I am beginning to develop upon a tested and stable code. Please be warned this is code that automates stuff for me, so you will be probably modifying it to fit your django configuration, tools, and deployment … -
Django translations for lazy programmers
I came to a dirty but practical solution for one minor project I had to develop for a client who wanted a website with i18n capabilities and also needed to have the different translations for each candidate values each in a different field, in the same model. That is, one field for each language. Here in this post I explain how to achieve it. Let's say we have some models with some fields we want to be duplicated, one for each language. In this example, we will store english (en), spanish (es) and french (fr): class MyObject(models.Model): name = models.CharField(max_length=50) title_en = models.CharField(max_length=50) title_es = models.CharField(max_length=100) title_fr = models.CharField(max_length=100) description_en = models.CharField(max_length=100) description_es = models.CharField(max_length=100) description_fr = models.CharField(max_length=100) class MyOtherObject(models.Model): name = models.CharField(max_length=50) content_en = models.CharField(max_length=200) content_es = models.CharField(max_length=200) content_fr = models.CharField(max_length=200) Notice we append a suffix to each field consisting of an underscore plus the language code. It is important to set the field names this way, as we are going to use a template tag that uses this suffix to find the proper translated field. Next thing to do is add a new TRANSLATION_FIELDS setting that will contain all the field names for ALL your model fields that … -
My thoughts on DjangoCon Berlin 2010
During this past week I attended DjangoCon, which took place in Berlin thanks to the German Django Association, a non-profit organization founded by german djangonauts. Interesting talks about Django, WSGI, NoSQL, testing, CouchDB, MongoDB, South or front-end design, to name a few. And in the evening or night, geeks gathered in Berlin pubs for beers and fun. I found a relief in meeting so many other people using Django, we djangonauts are a sort of lonely rangers here in Spain. The community is expanding, at the same pace that Django project is growing. In fact, it has already become a grown up in the open source ecosystem, and I think this fact is one of the main reasons that brought Jacob Kaplan-Moss give the first talk in the opening day about how we, Django users/developers/commiters, have to behave with the project itself and to the eyes of the others. The pony, a silly mascot that can be embarrassing to somebody (picture a girl asking her parents to buy her a pony, or a gay decorating his bedroom with stuffed animals, and you won't find the scene much related to guys with beards, pirates, ninjas or geeks hacking python) is precisely … -
New release of django-nomadblog
My Django blogging app, django-nomadblog, is sporting a new look after I added many features I needed for some of my present and future project developments. Mainly, I wanted to turn this app into a multiple blogging system, which means I am able to create and manage multiple blogs from the same installation, via admin interface. The implementation of this followed some improvements in the code and the modularity of the app itself. To upgrade this django blog to the new version of django-nomadblog, I should have created a migration using South, for example. But considering the small size of the database and the project inn general, I went the lazy way and created a fixture from the old database, edited by hand to meet the new models and relationships, and imported it to a fresh database. My punishment for being lazy was missing to update django.contrib.sites to replace the default example.com with nomadblue.com, and to include the data related to the projects site section in the fixture. I'll never learn. -
Using disqus comments and django-localeurl
Lately I have added comments to my company blog. We have it localized, so things turned out to be not so straight forward as one can think. django-localeurl This neat piece of code allows us to localize our URLs. You can find it in its bitbucket repository. So, in my blog I have four languages (english, catalan, spanish and french), each one with a different prefixed URL: http://example.com/blog/post_slug/ http://example.com/ca/blog/post_slug/ http://example.com/es/blog/post_slug/ http://example.com/fr/blog/post_slug/ Note that the english version doesn't have any prefix actually; this is a default from django-localeurl but you can change it if you want. disqus url So we want to include, of course, comments to our blog, and we are going to use disqus, a well-known service that makes our life more enjoyable without having to carry the burden of spam comments, implementing all the ubiquitous facebook, twitter, and many more logging services, to name a few. When using the universal JavaScript embed code, by default this script uses window.location to send the URL of the current page. As long as we are using localized URLs, if we don't modify this behavior then each localized URL would have its own comments. Hopefully, we can specify our URL with the … -
Translated text images for lazy programmers
In a previous post about django translations in this blog, I shared how to achieve a quick system that allowed me to manage translations stored in models and served using a template tag. In this post I will explain how to serve images that contain translated text and, hence, a localized image exists for each language. In my case, images are referenced from <img> HTML tags in templates and from CSS files. First of all we must create a basic structure in our img/ and css/ media folders, creating inside a directory for each language code we will use. For example, if we have two languages -- english and spanish -- we would create img/en/, img/es/, css/en/ and css/es/. In the CSS folders, the same files must be initially copied. If we have, for instance, just one style.css file, it must be both in css/en/style.css and css/es/style.css: css/ en/ style.css es/ style.css For the images, we should create the images that will be translated into each language code folder. All CSS files will reference the non-translated images in the same way, but their own file path to the translated image. I'll give an example. Let's say we have one background … -
django-propaganda: simple newsletter app
Hey you, political leader, founder of a new religion or spiritual guru! With this application, your acolytes will receive the official organizational propaganda pamphlets right into their inboxes. Keep them updated with the Truth! In a recent fever that drove me to program a system for the marketing department at my Barcelona SEO company, I developed a project that integrates Django admin to create basic versions of newsletters, manage the subscribers, and queue emails for later delivery using Celery workers and Amazon SES as platform. So now I published on GitHub the part that manages the basic models and functions: https://github.com/nabucosound/django-propaganda/ This simple Django application is made to be used for trivial newsletter (pamphlets) deliveries with your information (propaganda), where you supply the raw content (both plain text and HTML versions) to be delivered. Subscribers will then receive the emails you send. In the coming days I will maybe open source code for a sample project using the app, as well as all that components to finish the subscriber mailing cycle, or perhaps write a post with the instructions that I found useful to achieve that. In the meantime, I uploaded django-propaganda to the Python index, so that can easily … -
Asynchronous email delivery with Django, Amazon SES, Celery and Supervisord
A few weeks ago, I released a simple Django app to manage models for simple newsletters. The package itself is blatantly useless if we do not use it on a project that integrates with other parts, so I created a fully-equipped system that can create propaganda, assign it to subscribers and queue it ready to be sent whenever I need to. The architecture First, I have been using Amazon SES for a while to send newsletters to customers, both in-house and for clients and third-parties. It removes the hassle of maintaining SMTPs, email server management, network configuration, and meeting rigorous Internet Service Provider (ISP) standards for email content. So we will take profit of all those advantages, and make our life more simple and enjoyable. Second, we want a smooth and efficient delivery through concurrent background tasks, seamless for the user and detached from the front-end business logic. Whenever we press the "send" button we expect the system to return a confirmation response immediately — regardless of what's happening in the background — instead of getting the request frozen, waiting too much time for the email queue to be emptied and ending up with a web server timeout response. Celery … -
Useful Packages for Django projects (part 1)
This is the first of a series of posts about which libraries and tools we use for our Django development. Almost every Nomadblue project will have the following packages in their requirements.txt pip file. Probably most of the readers won't find much news here; however, eventually someone can realize he was missing something that could be leveraging their productivity or making life easier. Pillow As stated by the library documentation, Pillow is the "friendly" PIL fork by Alex Clark and Contributors. With Pillow you can stay cool as it installs smoothly using pip, and also you can sleep at night because somebody is maintaining the library in a healthy state through continuous integration, regular releases, bug fixing and development on github, and active participation on the Imaging-SIG. South When we started with Django (more than 5 years so far) there were a bunch of migration libraries out there, with different approaches. Andrew Godwin became a frequent flyer on the Django community, eventually winning the pulse and gathering the Djangonauts until South became a "must" or "de-facto" library to manage your database schema and data transitions. Worth mentioning that Andrew recently applied at kickstarter for a call to develop "a new, … -
Google Analytics tracking code into Django projects, the easy way
Creating a pluggable Django app to just embed the GA code seemed overkill to me, so I created this post as a quick reference for next Django web projects. The idea is creating a system that will add the tracking code under the following conditions: We have provided the ID and domain of our GA configuration. We are not running in settings.DEBUG mode. Settings variables The following settings must be defined on your settings.py. GOOGLE_ANALYTICS_PROPERTY_ID A string containing your ID on GA (e.g. UA-14845987-3). Get it from your configuration page: GOOGLE_ANALYTICS_PROPERTY_ID = 'UA-14845987-3' GOOGLE_ANALYTICS_DOMAIN This means the root domain you registered in Google Analytics. Even if you are configuring a subdomain (e.g. www.mydoamin.com or foo.mydomain.com) you must use the root domain. For instance, mydomain.com: GOOGLE_ANALYTICS_DOMAIN = 'mydomain.com' Context Processor Add this function to your context processors file: from django.conf import settings def google_analytics(request): """ Use the variables returned in this function to render your Google Analytics tracking code template. """ ga_prop_id = getattr(settings, 'GOOGLE_ANALYTICS_PROPERTY_ID', False) ga_domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', False) if not settings.DEBUG and ga_prop_id and ga_domain: return { 'GOOGLE_ANALYTICS_PROPERTY_ID': ga_prop_id, 'GOOGLE_ANALYTICS_DOMAIN': ga_domain, } return {} Add the context processor to your settings: TEMPLATE_CONTEXT_PROCESSORS = ( ... 'website.context_processors.google_analytics', ) Template …