Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Patterns: Model Inheritance
This post discusses the two flavors of model inheritance supported by Django, some of their use-cases as well as some potential gotchas. Overview When the queryset refactor landed a couple years ago, Django's ORM grew support for model inheritance. Model inheritance comes in two flavors, abstract and ... not. What are the important differences in how Django handles these two types of inheritance? Multi-table inheritance (not abstract) Directly extending a model results in two tables where the shared fields are stored in one table (the parent model's table) and the fields unique to the child model are stored on the child model's table. The child model contains a foreign key to the parent model and whenever queried automatically includes the joins. class Media(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() class Photo(Media): # note that Photo extends Media image = models.ImageField(upload_to='photos') class Video(Media): video = models.FileField(upload_to='videos') class VideoWithThumbnail(Video, Photo): """ Querying this object will result in 3 inner joins on filters/gets Saving/deleting will require at least 4 queries, but in my testing saving actually required 10 queries and deleting 13! """ pass Because of the way these items are stored in the database, it is possible to query against all media … -
Django Patterns: Model Inheritance
This post discusses the two flavors of model inheritance supported by Django, some of their use-cases as well as some potential gotchas. Overview When the queryset refactor landed a couple years ago, Django's ORM grew support for model inheritance. Model inheritance comes in two flavors, abstract and ... not. What are the important differences in how Django handles these two types of inheritance? Multi-table inheritance (not abstract) Directly extending a model results in two tables where the shared fields are stored in one table (the parent model's table) and the fields unique to the child model are stored on the child model's table. The child model contains a foreign key to the parent model and whenever queried automatically includes the joins. class Media(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() class Photo(Media): # note that Photo extends Media image = models.ImageField(upload_to='photos') class Video(Media): video = models.FileField(upload_to='videos') class VideoWithThumbnail(Video, Photo): """ Querying this object will result in 3 inner joins on filters/gets Saving/deleting will require at least 4 queries, but in my testing saving actually required 10 queries and deleting 13! """ pass Because of the way these items are stored in the database, it is possible to query against all media … -
Django static media always returning 404 not found
I spent too long tonight figuring out a weird problem. On a dev server, I was using django.views.static.serve to serve media files. But it was returning 404 (not found) for any file. The requests for media files weren’t even showing up in Django’s built-in server’s output. That had me baffled until I dug deep enough in Django’s code to figure it out. The ADMIN_MEDIA_PREFIX was the same as MEDIA_URL. That was it. Django’s built-in server doesn’t log requests for admin media, so that’s why there was no log output. The built-in server also handles admin media separately, so when I tried to request a media file, it intercepted and looked for it in the admin media. The solution is for the ADMIN_MEDIA_PREFIX to be different from MEDIA_URL, e.g. /media/ and /media/admin/. -
JOINs via denormalization for NoSQL coders, Part 3: Ensuring consistency
In part 1 and part 2 we introduced the concept of denormalization, materialized views and background tasks in order to emulate JOINs in the to-one direction on NoSQL databases. Now we'll talk about all remaining little but important snippets of the puzzle left over and discuss how to ensure that this method works in real world situation like server crashes. When to start background tasks? Let's first remember our current situation: We have a materialized view (i.e. the model PhotoUserView) containing denormalized properties of users (i.e. gender) and denormalized properties of photos (i.e. popularity). This materialized view is used to emulate JOINs in the to-one direction. Instances of PhotoUserView have to be kept up to date. If a user edits properties of a photo we have to start a background task in order to update all denormalized fields of the corresponding PhotoUserView entity If a user changes his/her gender (or her hair color) we have to start background tasks in order to update the denormalized gender of all PhotoUserView entities which point to that specific user Given this we have to answer when to start background tasks while keeping in mind that the connection / database / web server can … -
Django Admin Customization Examples
I've worked on a couple of projects recently that required some customization of the Django admin. One of the things that I love about Django's built-in admin is that it is created with a very extensible class-based structure. Here are some of the ways I was able to customize the admin to add functionality. Adding Buttons to the Change View One of the major features needed for a project was the ability to manage a workflow for a model. The model progressed through different status stages, and the admin team needed to be able to make decisions based on that current status. To handle this, I added some new buttons to the model's change view, and used my ModelAdmin and ModelForm subclasses to move the model around in the workflow accordingly. Customizing the Template In order to differentiate the workflow management options from the standard Admin delete & save buttons, I added a row of buttons directly above the standard delete & save row. I created a file in my templates directory with the path admin/myapp/mymodel/change_form.html that looked something like this: {% extends "admin/change_form.html" %} {% block after_related_objects %} {% if original.pk %} <div class="submit-row"> <p class="deletelink-box">Manage this request</p> {% … -
Testing GEODjango applications with Django 1.2
Today I lost 3 hours of my time trying to test a GeoDjango app. It all happened because I incorrectly created the gis template, by default expected to be called template_postgis Since Django 1.2 you don’t need to do anything special for testing GeoDjango apps. You used to need to set up the variable TEST_RUNNER. Don’t do this anymore! So I was happily executing: python manage.py test myapp and I was getting: Creating test database 'default'... Got an error creating the test database: ERROR: permission denied to copy database “template_postgis” Type 'yes' if you would like to try deleting the test database 'test_myapp', or 'no' to cancel: If you use Spanish you would get: Got an error creating the test database: se ha denegado el permiso para copiar la base de datos «template_postgis» I finally found how to fix this issue. The problem is that when I created template_postgis I didn’t set it to be a template. You can check it doing: SELECT * FROM pg_database; You can fix it doing: update pg_database set datistemplate=true where datname='template_postgis'; Finally this is how you should create your template_postgis for the first time: #!/usr/bin/env bash POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib/postgis-1.5 # Creating the template spatial database. … -
New Site! (Well, Most of One Anyway)
I haz a new site! I've been hacking at this for a few months now in my free time and it's finally in a position where I can replace the old one. Some of the features of the old site aren't here though, in fact this one is rather limited by comparison (no search, no snapshots, etc.) but the underlying code is the usual cleaner, better, faster, more extendable etc. so the site will grow beyond the old one eventually. So, fun facts about this new version: Written in Python, based on Django. 317133 lines of code Fun libraries used: Flot (for the résumé skillset charts) Neat stuff I added: A new, hideous design! A hierarchical tagging system A custom image resizing library. I couldn't find a use for the other ones out there. The Konami Code. Try it, it's fun :-) Stuff that's coming: Search Mobile image upload (snapshots) The image gallery will be up as soon as the shots are done uploading. Anyway, if you feel so inclined, please poke around and look for problems. I'll fix them as soon as I can. -
Diapositivas del Curso de Django en Deusto
Ya están en SlideShare las diapositivas del curso "Django: Disfruta programando" que han impartido Jaime Irurzun y Jorge Bastida en la Univesidad de Deusto. Aquí las tenéis y también podéis descargar el código del curso desde aquí. -
Vídeos de la Djangocon inspiradors
Aquests darrers dies he estat mirant els vídeos de la darrera Djangocon, com a tota conferència hi ha gent que vol una cosa més tècnica i gent que la troba massa tècnica, però particularment trob que al la quantitat de conferències i lightning talks que hi ha qui no ha trobat el que volia segurament és perquè no ha cercat prou. Jo he trobat molt interessants dues conferències, Scaling the World's Largest Django Application de la gent de DisqUs i Switching addons.mozilla.org from CakePHP to Django de la gent de Mozilla add-ons. M'interessen molt perquè mostre tant els problemes com la capacitat de Django per escalar per aplicacions molt grans, molt més grans del que estam acostumats per les nostres contrades. En el cas de Mozilla les xifres que donen el rendiment de programació estan en la línia del les meves pròpies recerques: una aplicació Django necessita de l'ordre de 3-5 vegades més línies de codi que per fer-la en PHP un framework com Cake. Aquests projectes tan grans fan que s'hagin de cercar solucions a problemes comuns d'escalabilitat. L'interessant d'aquests conferències és que et diuen tant els problemes que s'han trobat com les solucions. Pel Twitter he postejat algunes … -
Joining Mozilla
Happy to announce that at the end of October I'll be joining Mozilla. I'll be working in the web team on the Django sites. Excited to be working with a great team of people on some cool sites. -
Filtering Dropdown Lists in the Django Admin
It's not immediately obvious how to filter dropdown lists in the Django admin interface. This article will talk about how ForeignKeys can be filtered in Django ModelForms and then the Django admin. -
Filtering Dropdown Lists in the Django Admin
Automatically-generated dropdown lists can seem a little mysterious at first - particularly when you first want to customise what they contain in the Django admin. I'm going to go through a number of examples of increasing complexity of customising the content of dropdowns in various contexts: ModelForms, and then into the Django admin. Here are the models that the examples will work with. They're abbreviated and slightly modified versions of some models from the Swoop project I'm currently working on: class Area(models.Model): title = models.CharField(max_length=100) area = models.MultiPolygonField(blank=True, null=True) class Trip(models.Model): title = models.CharField(max_length=100) area = models.ForeignKey(Area) class Landmark(models.Model): title = models.CharField(max_length=100) point = models.PointField() class MountaineeringInfo(models.Model): trip = models.ForeignKey(Trip) area = models.ForeignKey(Area, blank=True, null=True) base_camp = models.ForeignKey(Landmark, blank=True, null=True) As you can see, we're using GeoDjango here - I'm not going to talk much about that here, but it should be obvious what's going on when we get it it. Note that these examples assume Django 1.2. Here are the cases that this article will cover: Filtering a forms.ModelForm's ModelChoiceField Filtering a Django admin dropdown Filtering a Django admin dropdown in an inline, based on a value on the main instance (phew!) Filtering a form's ModelChoiceField Consider this form: … -
Filtering Dropdown Lists in the Django Admin
Automatically-generated dropdown lists can seem a little mysterious at first - particularly when you first want to customise what they contain in the Django admin. I'm going to go through a number of examples of increasing complexity of customising the content of dropdowns in various contexts: ModelForms, and then into the Django admin. Here are the models that the examples will work with. They're abbreviated and slightly modified versions of some models from the Swoop project I'm currently working on: class Area(models.Model): title = models.CharField(max_length=100) area = models.MultiPolygonField(blank=True, null=True) class Trip(models.Model): title = models.CharField(max_length=100) area = models.ForeignKey(Area) class Landmark(models.Model): title = models.CharField(max_length=100) point = models.PointField() class MountaineeringInfo(models.Model): trip = models.ForeignKey(Trip) area = models.ForeignKey(Area, blank=True, null=True) base_camp = models.ForeignKey(Landmark, blank=True, null=True) As you can see, we're using GeoDjango here - I'm not going to talk much about that here, but it should be obvious what's going on when we get it it. Note that these examples assume Django 1.2. Here are the cases that this article will cover: Filtering a forms.ModelForm's ModelChoiceField Filtering a Django admin dropdown Filtering a Django admin dropdown in an inline, based on a value on the main instance (phew!) Filtering a form's ModelChoiceField Consider this form: … -
Filtering Dropdown Lists in the Django Admin
Automatically-generated dropdown lists can seem a little mysterious at first - particularly when you first want to customise what they contain in the Django admin. I'm going to go through a number of examples of increasing complexity of customising the content of dropdowns in various contexts: ModelForms, and then into the Django admin. Here are the models that the examples will work with. They're abbreviated and slightly modified versions of some models from the Swoop project I'm currently working on: class Area(models.Model): title = models.CharField(max_length=100) area = models.MultiPolygonField(blank=True, null=True) class Trip(models.Model): title = models.CharField(max_length=100) area = models.ForeignKey(Area) class Landmark(models.Model): title = models.CharField(max_length=100) point = models.PointField() class MountaineeringInfo(models.Model): trip = models.ForeignKey(Trip) area = models.ForeignKey(Area, blank=True, null=True) base_camp = models.ForeignKey(Landmark, blank=True, null=True) As you can see, we're using GeoDjango here - I'm not going to talk much about that here, but it should be obvious what's going on when we get it it. Note that these examples assume Django 1.2. Here are the cases that this article will cover: Filtering a forms.ModelForm's ModelChoiceField Filtering a Django admin dropdown Filtering a Django admin dropdown in an inline, based on a value on the main instance (phew!) Filtering a form's ModelChoiceField Consider this form: … -
Back to the Tables…
… or how table based layout still lives When I first started to write HTML (about ten years ago) the web has nothing common to the current one. Modem connections, IE4/IE5 were the major browsers and Netscape was far far away in the competition. These were dark ages for the web. CSS was a new [...] -
Python, Unicode and UnicodeDecodeError
In the years I've been developing in Python, Unicode seems to be the topic which causes the greatest amount of confusion amongst developers. Hopefully much of this confusion should go away in Python 3, for reasons I'll come to at the end; but until then, the UnicodeDecodeError is the bane of many developers' lives. -
Conheça o Django Packages
Conheça o Django Packages -
Conheça o Django Packages
Conheça o Django Packages -
Python, Unicode and UnicodeDecodeError
Unicode and Encodings OK, let's take a step away from text for a moment. I want you to think of a number between one and ten. Got one? Great - now, grab a pen and paper, and write it down.What number did you think of? Well, I thought of the number six. And when I wrote it down, it looks like this: Of course, if I were an ancient Roman (or possibly a clockmaker), I could have written this: They all mean the same thing - the number six. But we've written them in different ways. In other words, we've 'encoded' our idea of the number six in our head in three different ways - three different encodings.The separation of the idea of 'the number six' from its actual representation is basically all Unicode is. The Unicode Character set (UCS) defines a set of things (loosely, a set of letters) that we can represent. How we represent each of those letters is called an encoding. There's only one Unicode, but there are many encodings. In Unicode parlance, each of those 'things' (letters) are known as 'code points'. Unicode separates the characters' meaning from their representation.For historical reasons, the most common … -
Python, Unicode and UnicodeDecodeError
Unicode and Encodings OK, let's take a step away from text for a moment. I want you to think of a number between one and ten. Got one? Great - now, grab a pen and paper, and write it down.What number did you think of? Well, I thought of the number six. And when I wrote it down, it looks like this: Of course, if I were an ancient Roman (or possibly a clockmaker), I could have written this: They all mean the same thing - the number six. But we've written them in different ways. In other words, we've 'encoded' our idea of the number six in our head in three different ways - three different encodings.The separation of the idea of 'the number six' from its actual representation is basically all Unicode is. The Unicode Character set (UCS) defines a set of things (loosely, a set of letters) that we can represent. How we represent each of those letters is called an encoding. There's only one Unicode, but there are many encodings. In Unicode parlance, each of those 'things' (letters) are known as 'code points'. Unicode separates the characters' meaning from their representation.For historical reasons, the most common … -
Python, Unicode and UnicodeDecodeError
Unicode and Encodings OK, let's take a step away from text for a moment. I want you to think of a number between one and ten. Got one? Great - now, grab a pen and paper, and write it down.What number did you think of? Well, I thought of the number six. And when I wrote it down, it looks like this: Of course, if I were an ancient Roman (or possibly a clockmaker), I could have written this: They all mean the same thing - the number six. But we've written them in different ways. In other words, we've 'encoded' our idea of the number six in our head in three different ways - three different encodings.The separation of the idea of 'the number six' from its actual representation is basically all Unicode is. The Unicode Character set (UCS) defines a set of things (loosely, a set of letters) that we can represent. How we represent each of those letters is called an encoding. There's only one Unicode, but there are many encodings. In Unicode parlance, each of those 'things' (letters) are known as 'code points'. Unicode separates the characters' meaning from their representation.For historical reasons, the most common … -
Class-based Views with Django-Baseviews
I've always loved the concept of class-based views because views often become repetitive. There are a lot of common operations in a view that work best when they are defined once and reused. Class inheritance, in my opinion, is the best way to keep views DRY and allow you to focus on what makes each view different. At first, I used to break out pieces of functionality into their own functions in the views.py file. This worked okay, but I had to pass a lot of data around in the arguments and I had to do a lot of imports if I had functions from other app's views that I wanted to use in this app. This quickly became tedious. After seeing django-haystack use class-based views and really loving the way I could customize their behavior for my own project, I decided to start building some base views of my own to build on. While working on new Pegasus News apps, I started building up a set of class-based views that helped me stop repeating everything that the views had in common. Once the base views were in place, the process of creating new views for my apps because a … -
On DjangoCon 2010 and conferences in general
Sunlight Labs is a huge fan of Django. We use it in a majority of the projects we produce here and have released the source of numerous applications. So a few weeks ago a bunch of us eagerly packed our bags and flew out to Portland, OR for DjangoCon 2010. DjangoCon: The Good Parts Rethinking the Reusable Application Paradigm Alex Gaynor's talk "Rethinking the Reusable Application Paradigm", though a whirlwind of information, was one of the best of the conference. Reusable applications have long been a selling point of Django, but it is often quite difficult to use apps in any situation that would require the most basic of customization. Alex's talk covered the things that most frequently prevent apps from being reused and possible solutions to get around the limitations. The ideas he offered were both practical and enjoyably complex. I look forward to implementing some of them in our applications. Lightning Talks As always, the lightning talks were a highlight of the conference. It's a chance for people to show off novel solutions to problems or propose their crazy ideas. Some of the best included: Eric Holscher demoed Read The Docs, a documentation creation and hosting service. If … -
Django-taggit, le tag est mort, vive le tag ..
J'ai déjà fait, il y en fait 11 mois, un billet de la django app du mois sur une app de tag, django-tagging. Lorsque je l'ai testé, django-tagging était à la version 0.3. Aujourd'hui, elle est version 0.3.1. Et les derniers commit remonte à janvier 2010 ( ce sont ceux ayant aboutis à la ... -
JOINs via denormalization for NoSQL coders, Part 2: Materialized views
In part 1 we discussed a workaround for JOINs on non-relational databases using denormalization in cases for which the denormalized properties of the to-one side don't change. In this post we'll show one way to handle JOINs for mutable properties of the to-one side i.e. properties of users. Let's summarize our current situation: We have users (the to-one side) and their photos (the to-many side) Photos contain their users' gender in order to use it in queries which would need JOINs otherwise It's obvious that a solution for the problem of mutable properties on the to-one side has to keep denormalized properties up to date i.e. each time the user changes his/her gender (or more likely her hair color ;) we have to go through all of the user's photos and update the photos' denormalized gender. It is clear that we get into problems here if a user has thousands of photos to update because such an update would take too long. We need a scalable way to deal with such updates. Background tasks to the rescue One way to solve the update-problem is to start a background task each time a user changes his/her gender. It's clear that this …