Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Our Custom Mixins
UPDATE: We've released a Github repo and a PyPI package with our mixins. Feel free to fork and submit new ones through a pull-request. Let's just start out and say it, Class Based Views. Ooohhhh. Unfortunately the topic of class based views is thought of as somewhat of a dark art in the Django community. It doesn't help that the documentation is still lacking but I find a lot of people, especially on Reddit, refuse to use them. For whatever reason, it's a hard pill for some to swallow. Before DjangoCon 2011, we started playing with class-based views. At first they seemed like a nightmare and without decent docs, we got frustrated really quickly. Skip forward to today and I can't imagine writing old function-based views again. Some argue that the generic views are only for generic applications and that, somehow, their work is far too custom and complex to be handled in a generic class-based view. Based on my experience, 99% of the time, they would be wrong. We plan on covering generic class-based views extensively with GSWD. Today, I'd like to share some mixins we have cooked up, on a rather large client project, that have helped us … -
Welcome!
We are excited to finally launch the full website for this years DjangoCon Europe. Early bird registration as well as our call for papers is now open and we posted more details on our sponsoring packages.The early bird registration will run until the 31st of March, so sign up now! The call for paper will be until the 15th of April. -
Key-based cache expiration with Django
Last week, the team over at 37Signals wrote up an article on their newly implemented Key-based cache expiration system and it hit me: It's such a simple idea with obvious benefits, why hadn't I implemented a similar caching mechanism before? Being a Django user, the Rails code didn't make much sense to me but the concept certainly did - so here's my take on it with a quick Django example. -
Key-based cache expiration with Django
Last week, the team over at 37Signals wrote up an article on their newly implemented Key-based cache expiration system and it hit me: It's such a simple idea with obvious benefits, why hadn't I implemented a similar caching mechanism before? Being a Django user, the Rails code didn't make much sense to me but the concept certainly did - so here's my take on it with a quick Django example. Background I've just implemented this caching strategy for WhisperGifts for a re-launch that will go live in the next few weeks. We allow couples to publish an online gift list, then let people select items from that list. Pretty basic stuff, but rendering the gift list can require n+1 queries due to the way that my purchase data is kept. This hasn't been a big issue until now, when I've built new functionality and generally just extended things a bit. The cache strategy is so simple it's taken longer to write up here than it did to alter my existing codebase. My basic model is as follows: Registry, the top-level "collection" of items for each wedding. Item, of which there are many for each Registry Buyer, of which there are … -
Key-based cache expiration with Django
Last week, the team over at 37Signals wrote up an article on their newly implemented Key-based cache expiration system and it hit me: It's such a simple idea with obvious benefits, why hadn't I implemented a similar caching mechanism before? Being a Django user, the Rails code didn't make much … -
Generic Layouts in Crispy Forms
Just a quick tip and sanity check, today, about something I ran into with django-crispy-forms, the awesome new form library from Miguel Araujo. This morning, I converted the project we've been building for a client (currently some 1,700 or so files, counting templates, CSS, and icons) from django-uni-form to django-crispy-forms. It's a pretty painless transition, actually. Just do some find-and-replace across your files, basically changing any instance of uni- to crispy- (well, and form to forms), and you're good to go. Then, however, I wanted to convert two large forms that we have, which share 90% of their fields, to using the sharable Layout objects that django-crispy-forms gives us. Basically, the forms looked like this: class FirstForm(GenericAppFormForTheExample): ... def __init__(self, *args, **kwargs): ... self.helper = FormHelper() self.helper.layout = Layout( "field1", "field2", "special-field", [field3 through field20] class SecondForm(GenericAppFormForTheExample): ... def __init__(self, *args, **kwargs): ... self.helper = FormHelper() self.helper.layout = Layout( "field1", "field2", "special-field2", [field3 thorugh field20] Obviously that was a lot of repetition that we could cut out now that these inheritable layouts exist. By the way, I'm pretty sure this would have been possible in django-uni-form but likely not as friendly. First I started off by creating the shared resources. … -
You should Heroku
In mid-November me and my fiancee, Audrey Roy began our startup. We had been frustrated with trying to do on-line product research and came up with an idea to take the lessons learned from Django Packages / Open Comparison and apply them to a commercial effort. The result has been Consumer Notebook, and it's been a steadily growing success. We've been bootstrapping the project. That means supporting it with consulting and grinding away on it during our free time. That means 12-16 hour days of Python, Django, and Javascript coding, marketing, system administration, graphic design, communicating with users and vendors, and a thousand other tasks. Since we've had to explore new techniques for making things work on the backend and front end, that means we've needed to have a robust system that is trivial to deploy and certain to never go down. Which, of course, requires serious sys admin skills. The Big Problem I hate system administration work. Sys admin is boring. I find it tedious and dull. Devops doesn't make it easier/faster, it just makes it possible to do it at a large scale. Fortunately for me, my fiancee likes the sys admin side of things. However, she's got … -
You should Heroku
In mid-November me and my fiancee, Audrey Roy began our startup. We had been frustrated with trying to do on-line product research and came up with an idea to take the lessons learned from Django Packages / Open Comparison and apply them to a commercial effort. The result has been Consumer Notebook, and it's been a steadily growing success. We've been bootstrapping the project. That means supporting it with consulting and grinding away on it during our free time. That means 12-16 hour days of Python, Django, and Javascript coding, marketing, system administration, graphic design, communicating with users and vendors, and a thousand other tasks. Since we've had to explore new techniques for making things work on the backend and front end, that means we've needed to have a robust system that is trivial to deploy and certain to never go down. Which, of course, requires serious sys admin skills. The Big Problem I hate system administration work. Sys admin is boring. I find it tedious and dull. Devops doesn't make it easier/faster, it just makes it possible to do it at a large scale. Fortunately for me, my fiancee likes the sys admin side of things. However, she's got … -
15 Key Resources to Learn Django
Learning Python and Django is easy if you have the right resources at your fingertips. Coming from pretty much only having studied programming in school, I started working as a developer at Yipit with almost no web programming experience. In a little fewer than ten weeks, I’ve become comfortable navigating and making large changes to the whole Python/Django application code as well as contributing new features (interested in learning Django at Yipit? Join us!). While the learning process wasn’t gut-wrenching, I certainly ran into some hefty roadblocks that would have been almost insurmountable had coworkers not pointed me to the resources below: Comparing Python to Other Languages If you know another programming language already, you can easily leverage that knowledge by finding out the differences between Python and that other language, and then by focusing in on learning those differences. Python & Java – A Side by Side Comparison I knew enough Java already from college, and doing some quick reading online saved me a lot of time. I would highly recommend reading this article if you know Java already. It helped me form a mental road-map of what areas to focus on. Also, the Python wiki has a good … -
AJAX Autocomplete Search with Django and jQuery
Let's say you have some data that you want to autocomplete in a text field as the user types. This is what your Django model might look like if you were searching for drug names: from django.db import models class Drug(model.Model): rxcui = models.IntegerField() short_name = models.CharField(max_length=50) is_brand = models.IntegerField(max_length=1) It's very likely that your data is in a different format (csv or pipe delimited), like this: Rxcui|Short Name|Is Brand 1234 |Advil |1 So we need to import that data. A database copy command (postgres, mysql, sqlite) will not deal very nicely with our Django auto-incrementing keys, so we need to add the data using a django view, such as this: import csv from myproject.main.models import Drug def load_drugs3(file_path): "this loads drugs from pipe delimited file with headers" reader = csv.DictReader(file_path) for row in reader: drug = Drug(rxcui=row['Rxcui'], short_name=row['Short Name'], is_brand=row['Is Brand']) drug.save() Now load the django console and import the data: $ python manage.py shell $ from main.view import load_drugs $ load_drugs('/absolute/path/to/pipe/file.txt') Cool. Now we need to actually write the template where the search is. We'll use jQuery Autocomplete because that's what the cool kids do. Let's first import jQuery and jQueryUI in our base template: Now let's add … -
Change Request Workflow
Before we start, let me explain a bit about what the app we're covering here is. It's a geo-spatial database, basically, of Points of Interest (POIs) for housing communities that we developed for a client of ours (or, rather, are still developing). Users and editors can both enter Points into the database, which is PostgreSQL with PostGIS, and then they can be associated with any community. Obviosuly, though, that leads to the problem of Community A editing a POI and Community B showing that data without their knowledge, so we'd like to have an editor look at the changes first. That's the need that lead to our workflow. Models First, let's start with the models. class POIAbstract(LumberjackModel, models.Model): category = models.ForeignKey(Category, related_name="%(class)s_points") name = models.CharField(max_length=255) address = models.CharField(max_length=255) address2 = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=100) state = USPostalCodeField() zip_code = models.CharField(max_length=10) phone = PhoneNumberField(blank=True, default="") url = models.URLField(blank=True, default="") point = models.PointField(blank=True, null=True, editable=False) objects = models.GeoManager() class Meta: abstract = True def __unicode__(self): return self.name @property def coords(self): """ Return tuple of lat,lng """ if self.point: return (self.point.get_coords()[1], self.point.get_coords()[0]) return (None, None) @property def full_address(self): """ Return a string of the full address """ addresses = [self.address, self.address2, self.city, … -
AJAX Autocomplete Search with Django and jQuery
-
AJAX Autocomplete Search with Django and jQuery
Let’s say you have some data that you want to autocomplete in a text field as the user types. This is what your Django model might look like if you were searching for drug names: 1 2 3 4 5 from django.db import models class Drug(model.Model): rxcui = models.IntegerField() short_name = models.CharField(max_length=50) is_brand = models.IntegerField(max_length=1) It’s very likely that your data is in a different format (csv or pipe delimited), like this: 1 2 Rxcui|Short Name|Is Brand 1234 |Advil |1 So we need to import that data. A database copy command (postgres, mysql, sqlite) will not deal very nicely with our Django auto-incrementing keys, so we need to add the data using a django view, such as this: 1 2 3 4 5 6 7 8 import csv from myproject.main.models import Drug def load_drugs(file_path): "this loads drugs from pipe delimited file with headers" reader = csv.DictReader(open(file_path)) for row in reader: drug = Drug(rxcui=row['Rxcui'], short_name=row['Short Name'], is_brand=row['Is Brand']) drug.save() Now load the django console and import the data: 1 2 3 $ python manage.py shell $ from main.view import load_drugs $ load_drugs('/absolute/path/to/pipe/file.txt') Cool. Now we need to actually write the template where the search is. We’ll use jQuery Autocomplete because that’s … -
AJAX Autocomplete Search with Django and jQuery
Let’s say you have some data that you want to autocomplete in a text field as the user types. This is what your Django model might look like if you were searching for drug names: 1 2 3 4 5 from django.db import models class Drug(model.Model): rxcui = models.IntegerField() short_name = models.CharField(max_length=50) is_brand = models.IntegerField(max_length=1) It’s very likely that your data is in a different format (csv or pipe delimited), like this: 1 2 Rxcui|Short Name|Is Brand 1234 |Advil |1 So we need to import that data. A database copy command (postgres, mysql, sqlite) will not deal very nicely with our Django auto-incrementing keys, so we need to add the data using a django view, such as this: 1 2 3 4 5 6 7 8 import csv from myproject.main.models import Drug def load_drugs(file_path): "this loads drugs from pipe delimited file with headers" reader = csv.DictReader(open(file_path)) for row in reader: drug = Drug(rxcui=row['Rxcui'], short_name=row['Short Name'], is_brand=row['Is Brand']) drug.save() Now load the django console and import the data: 1 2 3 $ python manage.py shell $ from main.view import load_drugs $ load_drugs('/absolute/path/to/pipe/file.txt') Cool. Now we need to actually write the template where the search is. We’ll use jQuery Autocomplete because that’s … -
Change Request Workflow
Before we start, let me explain a bit about what the app we're covering here is. It's a geo-spatial database, basically, of Points of Interest (POIs) for housing communities that we developed for a client of ours (or, rather, are still developing). Users and editors can both enter Points into the database, which is PostgreSQL with PostGIS, and then they can be associated with any community. Obviosuly, though, that leads to the problem of Community A editing a POI and Community B showing that data without their knowledge, so we'd like to have an editor look at the changes first. That's the need that lead to our workflow. Models First, let's start with the models. class POIAbstract(LumberjackModel, models.Model): category = models.ForeignKey(Category, related_name="%(class)s_points") name = models.CharField(max_length=255) address = models.CharField(max_length=255) address2 = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=100) state = USPostalCodeField() zip_code = models.CharField(max_length=10) phone = PhoneNumberField(blank=True, default="") url = models.URLField(blank=True, default="") point = models.PointField(blank=True, null=True, editable=False) objects = models.GeoManager() class Meta: abstract = True def __unicode__(self): return self.name @property def coords(self): """ Return tuple of lat,lng """ if self.point: return (self.point.get_coords()[1], self.point.get_coords()[0]) return (None, None) @property def full_address(self): """ Return a string of the full address """ addresses = [self.address, self.address2, self.city, … -
Release 0.6.7
We just released LFS 0.6.7. This is a yet another bugfix release. Changes Bugfix: fixed displaying of manual topsellers (Maciej Wi?niowski) Bugfix: topsellers - avoid empty product_id for discounts (Maciej Wi?niowski) Bugfix: take care of variants for deliverability (Maciej Wi?niowski) Bugfix: fixed bug causing strange behaviour while creating variants (Maciej Wi?niowski) Bugfix: fixed product filtering for product management views; #issue 142 Bugfix: added csrf token to active-images-update-form Bugfix: fixed lfs_init for Postgres; issue #129 Added translations for filter buttons and fix for topseller positions (Maciej Wi?niowski) Updated polish translations (Maciej Wi?niowski) Updated german translations News: We have setup a GitHub mirror of LFS. The docs are running on our own domain now (still hosted on RTD) and have a new layout: http://docs.getlfs.com/ Information You can find more information and help on following locations: Documentation on PyPI Demo Releases on PyPI Source code on bitbucket.org and github. Google Group lfsproject on Twitter IRC -
Yet another tutorial for building a blog using Python and Django - Part 1
While I’m extremely fond of Perl for quick hacks and scripts, and have used PHP a fair amount for web development purposes (both on its own and with the CodeIgniter framework), there is one language I love above all others, and that’s Python. I’ve found that, when compared to PHP or Perl, at least for me, it’s a lot easier to “get into the zone” when programming in Python, the code I produce tends to be a lot more readable and easier to follow, and the interactive interpreter makes it really easy to figure out what’s going on in a way that just isn’t possible with PHP or Perl. Also, Python was always designed to be an object-oriented language, and IMHO has a better object model than either Perl or PHP. While it would be fair to say that Python doesn’t have a single web development framework that monopolises developer’s attention the way Rails does for Ruby programmers, Django is undoubtedly the best-known Python framework. It’s solid, easy to use, and has the best documentation of any web development framework I’ve ever seen (don’t get me wrong, CodeIgniter in particular has very good documentation, but Django’s is exceptional). In this … -
Django class based views (VII) - Epíleg
El món de les class based views dóna per molt, la possibilitat de sobreescriure funcions, canviar paràmetres i anar combinant mixins fins a obtenir el que necessitam ens permet reutilitzar molt de codi i de manera elegant. En aquest darrer post de la sèrie veurem algunes de les situacions més habituals en les que ens podem trobar i la facilitat amb que es resolen. El formulari per defecte no és el que vull Sovint quan editam un objecte mitjançant un formulari ens trobam que hi ha camps que no volem que s'editin. A l'exemple que hem fet servir fins ara imaginem que no volem que una vegada s'ha crear l'slug es pugui modificar. Per fer això el que hem de fer és crear un formulari nou. Com que es bo tenir les coses organitzades ho farem dins el fitxer forms.py class SampleEditForm(forms.ModelForm): class Meta: model = Sample exclude = ('slug',) i llavors a la classe que implementa l'edició li direm que agafi aquest formulari per a editar l'objecte from forms import SampleEditForm class SampleUpdateView(UpdateView): model = Sample success_url = reverse_lazy('tutorial_list_sample') form_class=SampleEditForm Volem poder filtrar/ordenar els resultats El ListView és un component idial per a fer cerques i filtres. Amb una … -
Django class based views (VI) - Lists
En aquesta sisena entrega (que hi ha algú per aquí ho ja us heu dormit tots?) veurem com podem mostrar llistes d'objectes que sovint podem trobar amb els CRUD. Per a mostrar llistats (paginats o no) Django ens proporciona la classe ListView que es pot trobar a dango.views.generic.list. Aquesta classe és hereva de MultipleObjectTemplateResponseMixin i de BaseListView. BaseListView és el que la la feina, ja que és fill de MultipleObjectMixin i de View implementant-ne el mètode get. Com les vistes orientades als CRUD també en aquest cas tenim una plantilla per defecte, formada pel nom del model i el sufixe '_list'. El que més ens interessa són doncs els mètodes i atributs de MultipleObjectMixin. Primer de tot, però anem a fer-ho fàcil, mostrarem la llista dels objectes que hem creat al post anterior: A l'url: url(r'^tutorial/sample/list/$', SampleListView.as_view(), name='tutorial_list_sample'), i al views.py podem fer from django.views.generic.list import ListView class SampleListView(ListView): model = Sample i ara haurem de definir la plantilla que tindrà com a nom sample_list.html, primer, però és convenient conèixer quines variables es passen al context, a saber: paginator page_obj is_paginated object_list Els valors poden canviar en funció de si tenim paginació o no, però les variables que tenim són … -
Django class based views (V) - CRUD
Creant un CRUD En aquesta cinquena part veurem com podem crear tot el relacionat amb un manteniment, el famós CRUD (Create, Retreive, Update, Delete). La part de Retreive ja l'hem vista a l'article anterior, però hi tornarem per a que ens quedi un exemple complet. Partirem del següent model: class Sample(models.Model): """this is just a sample model""" slug = models.SlugField(max_length=50, unique=True) name = models.CharField(max_length=100) ammount = models.IntegerField() comments = models.TextField(blank=True, null=True) class Meta: verbose_name = 'Sample' verbose_name_plural = 'Sample' def __unicode__(self): return self.name Django a més de DetailView ens proporciona les següents vistes ja construïdes per fer aquest tipus de tasques: * `CreateView` que gestiona la creació * `UpdateView` que gestiona l'actualització * `DeleteView` gestiona l'esborrat Comencem! Creació Definim primer la url url(r'^tutorial/sample/create/$', SampleCreateView.as_view(), name='tutorial_create_sample'), Hem anomenat a la nostra classe SampleCreateView així que la definirem al views.py from django.views.generic.edit import CreateView from main.models import Sample class SampleCreateView(CreateView): model = Sample Amb això Django ja ens crearà internament un formulari i l'intentarà presentar a una plantilla que es construeix amb el nom del model i el sufixe _form, és a dir, en el nostre cas sample_form.html passant com a variable de context el formulari creat form Si volem fer via … -
Dummies doing dummy things
It can often be interesting to test hypothetical situations. So the other day I did a little stress test to see how Evennia handles many players. This is a follow-up to the open bottlenecks post.Evennia, being based on Twisted, is an asynchronous mud server. This means that the program is not multi-threaded but instead it tries to divide up the code it runs into smaller parts. It then quickly switches between executing these parts in turn, giving the impression of doing many things at the same time. There is nothing magical about this - each little piece of code blocks the queue as it runs. So if a particular part takes too long, everyone else will have to wait for their turn. Likewise, if Twisted cannot flip through the queue as fast or faster than new things get added to it, it will start to fall behind. The good thing is that all code in the queue will run, although if the event loop cannot keep up there will be a noticeable delay before it does. In a mud, this results in "lagging" (in addition to whatever lag is introduced by your network connection). Running Evennia with a handful of … -
My PyCon 2012 Schedule
Here I was thinking that this year's PyCon wasn't going to be so busy because I didn't submit a talk or tutorial. Ha! What the heck was I thinking? Here's what I've already got in the works. Wednesday, March 7th Me and Audrey are driving up from Los Angeles. I've wanted to do this drive for a while, so this is very exciting. We'll arrive in the evening and hopefully tag up with friends old and new. Thursday, March 8th I'm moderating the Code Reuse panel of the Python Web Summit. Have you submitted a question yet? In the evening we'll be helping assemble bags for the conference. That's always a blast. Friday, March 9th PyCon really begins! I'll be at the keynotes, and then the talks begin. These are some of the talks I'm really leaning towards watching: Introduction to Metaclasses The Art of Subclassing Data, Design, Meaning Code Generation in Python: Dismantling Jinja The problem, of course, is that all the talks look awesome. Missing some of these talks is going to hurt. In the evening we're going to the New Relic/Loggly/Skull Candy party and hang out at the (in)famous TIP BOF. Saturday, March 10th I'll be at … -
My PyCon 2012 Schedule
Here I was thinking that this year's PyCon wasn't going to be so busy because I didn't submit a talk or tutorial. Ha! What the heck was I thinking? Here's what I've already got in the works. Wednesday, March 7th Me and Audrey are driving up from Los Angeles. I've wanted to do this drive for a while, so this is very exciting. We'll arrive in the evening and hopefully tag up with friends old and new. Thursday, March 8th I'm moderating the Code Reuse panel of the Python Web Summit. Have you submitted a question yet? In the evening we'll be helping assemble bags for the conference. That's always a blast. Friday, March 9th PyCon really begins! I'll be at the keynotes, and then the talks begin. These are some of the talks I'm really leaning towards watching: Introduction to Metaclasses The Art of Subclassing Data, Design, Meaning Code Generation in Python: Dismantling Jinja The problem, of course, is that all the talks look awesome. Missing some of these talks is going to hurt. In the evening we're going to the New Relic/Loggly/Skull Candy party and hang out at the (in)famous TIP BOF. Saturday, March 10th I'll be at … -
Django class based views (IV)
Començam a lligar les class views amb els models de dades, que això es posa cada cop més interessant. Fins ara hem vist un ús de les class views molt genèric, és a dir, amb el que sabem podem mostrar planes webs i gestionar el treball amb formularis. Es comú en la majoria d'aplicacions web modernes que les dades venguin d'algún lloc, d'una base de dades per exemple. Així que la gent de Django han creat tota una sèrie de mixin i vistes específices per a simplificar-ne el treball. Mostrar un objecte Suposem que volem mostrar les dades que tenim d'un usuari. Com sabeu el model User de Django conté les dades dels usuaris i es troba a django.contrib.auth.models. Voldríem que en especificar-ne la clau primària a la url poder mostrar les dades de l'usuari corresponent. És a dir, es tracta de mostrar informació que es correspon a urls d'aquest tipus '^prefix/(?P<pk>\d+)/$' o també '^prefix/(?P<slug>[-w]+)/$' Django ens proporciona la classe DetailView per fer precisament això. És a dir, per estalviar-nos la major part de la feina de cercar l'objecte que es correspon amb la clau primària o l'slug i passar-ho a la plantilla per a la seva presentació. Per si … -
Browser ID
Browser ID is Mozillas new federated authentication system. This screencast walks you through using the django-browserid package to do your authentication, and attach it to the built in Django auth systemWatch Now...