Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Abstract Models and Dynamicly Assigned Foreign Keys
Model inheritance enables creating extensible apps. You can define a reusable core app which includes base.py with abstract models and models.py with models extending the abstract ones and inheriting all the features. In the specific project you can either use the core app directly, or create a specific app which models extend from the base abstract models of the core app and additionally introduce new features.This is a quick example skipping all the unrelated parts like settings, urls, and templates:core_projectappsplayerbase.pyfrom django.db impport modelsclass PlayerBase(models.Model): name = models.CharField(max_length=100) class Meta: abstract = Truemodels.pyfrom core_project.apps.player.base import PlayerBaseclass Player(PlayerBase): passspecific_projectappsplayermodels.pyfrom core_project.apps.player.base import PlayerBaseclass Player(PlayerBase): points = models.IntegerField()The concept works fine until you need to use foreign keys or many-to-many relations in the abstract models. As Josh Smeaton has already noticed, you can't set foreign keys to abstract models as they have no own database tables and they know nothing about the models which will extend them.Let's say, we have the following situation: GameBase and MissionBase are abstract models and the model extending MissionBase should receive a foreign key to the model extending GameBase.Thanks to Pro Django book by Marty Alchin, I understood how the models get created in the background. By default, all … -
Mejoras en django.es y feed de la comunidad
Sois varios los que nos habéis pedido un feed con las últimas entradas de los blogs la comunidad. Pues aquí lo tenéis. También hemos introducido algunas mejoras en django.es para que las páginas de nuestro sitio web carguen más rápido, y parece que lo hemos conseguido :) Por ejemplo los feeds de la página de inicio ya no se cargan en el lado del servidor al procesar la página sino mediante javascript una vez se ha cargado el documento. -
Open Government Hackathon: Chicago, March 29-31
Sunlight Labs is proud to be hosting the first ever Open Government Hackathon, March 29-31 in Chicago. This will be a 48 hour sprint where developers that are interested in contributing to an open source project that will free or otherwise enhance government data can gather to brainstorm and hack on things. Who Should Attend? Anyone that is interested in contributing to an open source project that will free or otherwise enhance government data can gather to brainstorm and hack on things. Although the sprint takes place at PyCon you don't have to be attending the conference to join us. Participation is free and open to anyone. What Happens at the Open Government Hackathon? The nature of the sprint will be fairly freeform, two Sunlight Labs members will be on hand guiding users that want to contribute to opening up the government. Users can come to the sprint without any background and we would help coordinate them and place them on a project where there skills would be useful (there is always a ton of scraping that needs to be done, building mini-web apps to showcase gov't data, etc.) Most likely we'll spend the first session on Sunday talking about … -
Blango, django-geonames, oauthsp and wapi hosted at GitHub
I've finished moving some of my git repos to GitHub. You can now check Blango, django-geonames, oauthsp and wapi from there. Those are, from now on, the official repos. The old ones at byNotes have already been closed. -
High Performance Media Merging with Django, Nginx and Memcached
I admit it – I’m a performance junkie. I can’t stand code that just works but performs poorly. Being said, I recently fell in love with Django (a fantastic Python powered web application framework). In one of my current projects – xarmory.com – the number of requests for static resources issued during page load began to bother me. The project makes intensive use of jQuery and it’s my personal belief that Django + jQuery is a match made in heaven. When working with jQuery you will find yourself often in the situation to rely in cool little jQuery plugins – each distributed as a seperate javascript file of course. When a project grows, those files begin to add up. In the case of xarmory.com we now had eleven javascript references in the header section of the page. Although the individual files are were only 3-11k in Size, the request overhead for all those tiny files became unacceptably in my eyes. To alleviate the problem I decided to resort to a simple solution and just merge the individual script files into a single file. A pretty common practice. Before reinventing the wheel I surfed the net for existing solutions and found … -
Leaving byNotes
Well, let me start by explaining all those mails about byNotes I haven't answered in the last few months. Around mid November I got contacted by the recruiting staff of a social network. At that time, I was still working in the project for my degree (computer science students in Spain are required to write a project for the university in order to get the degree) and I wanted to concentrate on it, but I decided to just take the interviews just in case. They finally told me they wanted me to join them and we agreed to continue the negotiations once I had finished my project. Fast forward to January, my project is done and christmas holidays are gone, time to reestablish negotiations. Salary is good, schedule is very good (telecommuting 99% of the time) but there's something bad: I must leave byNotes, since management considers it's competing with them. It wasn't an easy decision, but it was the best option. byNotes has been very fun, but also such a time drain to me, and I haven't got any single eurocent from it. Plus, I'm a coder, not a designer nor a business guy, and I don't have too … -
Django Tips – Unique Date Querysets
I swear this particular feature of querysets was made especially for the archive listing of a blog. You know, the month and year listing in the side bar for all your previous posts. This solves that problem exactly. -
Django LogEntry to the rescue
If you use Django's admin application, you're familiar with its "Recent Actions" sidebar. It gives a simple summary of your latest edits, including clickable links to the relevant objects (not any ones you deleted, naturally, but ones you added or changed). It's probably not something you look at very often, unless you do such intensive work in the admin that you lose track of things. Django stores that log data (via the admin's LogEntry model) for all admin users, a fact which has caused me to repeatedly daydream about writing a custom view or two to display it. In other words, I'd like to let superusers browse all object editing history. Because sometimes you need to answer questions like "When was that changed?" and/or "Who changed it?" Today at work, a question arose about some data that was deleted via the admin several months ago. It didn't need recovering, we just needed a record of its deletion. An audit trail. LogEntry to the rescue! Via manage.py shell and manage.py dbshell I was able to do some quick spelunking and get exactly the records we needed. It was a very positive experience. I love being able answer questions that begin, "Paul, … -
Announcing django-filter
Django-filter is a reusable Django application I have been working on for a few weeks, individuals who follow me on Github may have noticed me working on it. Django-filter is basically an application that creates a generic interface for creating pages like the Django admin changelist page. It has support for defining vairous filters(including custom ones), filtering a queryset based on the user selections, and displaying an HTML form for the filter options. It has a design based around Django's ModelForm.You can get the code, as well as tests and docs over at Github. For all bug reports, comments, and other feedback you can send me a message on Github(or message me on IRC) until I figure out a proper bug tracking system.Enjoy. -
FE-Plugin with multilingual TYPO3
I always forget how to force a frontend plugin to display the texts localized through $this->pi_getLL($key). This is how it works: class tx_extkey_piX extends tslib_pibase { function main() { $this->sys_language_uid = (int) t3lib_div::_GP('L'); ... } } -
FE-Plugin with multilingual TYPO3
I always forget how to force a frontend plugin to display the texts localized through $this->pi_getLL($key). This is how it works: class tx_extkey_piX extends tslib_pibase { function main() { $this->sys_language_uid = (int) t3lib_div::_GP('L'); ... } } -
FE-Plugin with multilingual TYPO3
I always forget how to force a frontend plugin to display the texts localized through $this->pi_getLL($key). This is how it works: class tx_extkey_piX extends tslib_pibase { function main() { $this->sys_language_uid = (int) t3lib_div::_GP('L'); ... } } -
Training Video of the week
Thoughts David did a great job explaining many of the crucial pieces of web site scaling. Our discussion afterward focused on how we can structure our site to handle more requests without more hardware. We also talked about David’s point on the importance of profiling code to find the slow spots. I know I have spent too much time trying to optimize code that was only a small part of the running time. -
EuroDjangoCon
Just a quick note to say I just registered to go to EuroDjangoCon! Head over to http://euro.djangocon.org/ to sign up for the earlybird prices! I can't wait, it's going to be Awesome. :) Hope to see you all there! -
Missing django-admin's startproject Command?
Did you just notice your "django-admin.py startproject new_project" command does nothing but to remind you to read the help docs? Well, clear your existing environment variable "DJANGO_SETTINGS_MODULE" and you'll have it again.Django takes away "startproject" command if it realizes you are already working with an existing project. Not sure what the purpose is, but its there. -
A Second Look at Inheritance and Polymorphism with Django
Previously I wrote about ways to handle polymorphism with inheritance in Django's ORM in a way that didn't require any changes to your model at all(besides adding in a mixin), today we're going to look at a way to do this that is a little more invasive and involved, but also can provide much better performance. As we saw previously with no other information we could get the correct subclass for a given object in O(k) queries, where k is the number of subclasses. This means for a queryset with n items, we would need to do O(nk) queries, not great performance, for a queryset with 10 items, and 3 subclasses we'd need to do 30 queries, which isn't really acceptable for most websites. The major problem here is that for each object we simply guess as to which subclass a given object is. However, that's a piece of information we could know concretely if we cached it for later usage, so let's start off there, we're going to be building a mixin class just like we did last time:from django.db import modelsclass InheritanceMixIn(models.Model): _class = models.CharField(max_length=100) class Meta: abstract = TrueSo now we have a simple abstract model that … -
Migrating Django models with south and converting data
I use South whenever a model needs to be changed. One thing that is not really documented in the South documentation is how to convert data. After some trial and error I found a way to use Django QuerySets to access both the old and new models to convert data. For example, I used to have two models defined like this: class Assignment(models.Model): course = models.ForeignKey(Course) name = models.CharField(max_length=100) class AssignmentEdition(models.Model): assignment = models.ForeignKey(Assignment) # ... other fields The way the assignments were defined, each edition of an assignment has the same name. I needed to change this into: class Assignment(models.Model): course = models.ForeignKey(Course) class AssignmentEdition(models.Model): assignment = models.ForeignKey(Assignment) name = models.CharField(max_length=100) # ... other fields Each edition has it’s own name. It’s still possible for editions to have the same name, but it is also possible to have a different name and still be an edition of the same assignment. During the migration I want each assignment edition to get the name of it’s assignment. One way to do this is to use SQL queries to get the names of the assignments and update the assignment edition names, but that’s not very Django-like. I want to use QuerySets. I … -
Create a Stand-alone Django Documentation Browser
I’m constantly quitting and changing browsers. I got tired of having to load up the Django Documentation. I found an easy way to keep up the Django docs by themselves. I use Fluid, a site-specific browser creator, for Google Reader, and I thought why not for this? When you launch Fluid, It asks you for a URL, a Name for the application, a location to save the application and what icon to use (it defaults to the web site’s favicon). I created my own PNG and made it the icon. Once you press the Create button, you can open the application by double clicking on it. To make the application a bit more flexible, open the preferences (command-,) and click on the Advanced icon. There you can add and change the urls that this application will go to. I changed the url to *.djangoproject.com/*. There you have it: a stand-alone browser of the Django documentation. -
7. Finishing the Weblog
This is part 7 of a series of posts on James Bennett's excellent Practical Django Projects. The table of contents and explanation can be found here Firstly, the comments framework has been re-written for 1.0. The documentation for it can be found here if you need to refer to it. That out of the way lets get into the meat of the chapter. There is now only one model for comments instead of two -
Field/column Queries in Django
Field/column Queries in Django -
My Django development environment
IDE After using a few other IDE‘s I settled down with Eclipse with Aptana plug-in as the IDE I use for peach³ development. This one environment has support for everything I need while developing a Django application: Python, HTML and JavaScript support is great, with code completion, including completion for the Ext.js javascript library. And I even have the idea that I’m not using the full power of Eclipse yet. By default, Eclipse and Aptana have no Python support, but it can be integrated with PyDev. The only thing missing to make it the best environment (in my opinion) is support for Django template tags: a Django template tag inside a HTML or JavaScript file usually results in an inline error message. But you can just ignore these error messages. For some of the most used Django management commands (runserver and test) I’ve defined ‘tools’ in the Eclipse interface and I can now start my development server or run the testsuite with a single click inside Eclipse. Here is how I set up the single-click runserver tool: In “Run > External Tools > External Tools…” I’ve added a new tool called “Django Runserver” and I set up the following on … -
ORD Camp a Huge Success
I was luck enough to be invited to attend ORD Camp this last weekend in blisteringly cold Chicago.  ORD Camp is an invite only, FooCamp style unconference targeted at geeks living in the Midwest. Having never attended a FooCamp style event I wasn't sure what to expect.  I can now say if you ever have the opportunity to attend an event like this it is well worth your time. As you can see from the attendee list it was a very diverse group of people, not just the usual crowd of notable Open Source geeks.  The amount of brain power in that room was simply amazing and I can't remember when I had as much fun.  Some sessions were presentations, others were just focused discussions.  Everything from how words work, brewing beer, life hacking, to what not to do as a startup.  While I loved the sessions the most fun was getting into random conversations ( some ended up being NSFW after midnight and many beers ) others were more typical.  Spent some time talking with people about PostgreSQL's advantages over MySQL, alternative business models, how a certain entrepreneur might improve the performance of their servers, etc. It is difficult … -
Running long processes in Django
My original issue was that I had this piece of code in my Django project that was taking way too long to run, sometimes even leading to a load time out. The particular situation happens very infrequently (at most once a week), so it was just a matter of getting the process to run successfully. Along the way, though, I learned a lot about spawning processes, distributed computing, and the different options we have in the Python community. The different approaches are just ways to get the processing to be done outside the Django process, of course. cron and queue cron I will first start with the recommended process of taking care of this issue. You can setup a cron job to run some code that checks every minute to see if there’s anything to process and then run the appropriate code. Cron jobs are pretty simple to setup and pretty effective. All you need to do is edit the crontab with the time intervals you want the service to be run and your code takes care of the rest. django-queue-service The cron part of this solution takes care of when the processing happens, but what handles why it happens? … -
Pinax update: breaks external dependencies
Have you been working off the Pinax trunk only to be surprised by the following message after an update: Error: No module named notification Basically what happened is summarized on the django-hotclub page, which I apparently should start paying closer attention to: http://code.google.com/p/django-hotclub/wiki/MovingToDistutils What this all means is that you will need to change your setup a bit to get Pinax to work in its new setup… What I had to do first was install pip and virtualenv sudo easy_install pip sudo easy_install virtualenv If you need to setup easy_install or you have any trouble with the following step, try updating python-setuptools sudo apt-get install python-setuptools You will also need to install git and bzr as mentioned in the wiki page. On my Ubuntu box, it was simple as installing git-core and bzr sudo apt-get install git-core sudo apt-get install bzr After that you need to run the following command to download the apps (Feb 6, typo fixed, thanks Vernon): sudo pip install -r pinax/requirements/external_apps.txt And then back to your normal: python manage.py syncdb python manage.py runserver (of course this is just on your dev box…) hope that helps. -
The taste of shame and humiliation
What a way to start the morning: Yup, that’s right; my former employer the Lawrence Journal-World – one of the most ground-breaking, award-winning, forward-looking, innovative news organizations in the world – is now serving pop-under ads. I really did think that my former bosses, friends, and colleagues there knew better. I can only hope this was a top-down do-it-or-lose-your-job edict, but even that smacks of the kind of dictatorial micromanagement I thought the company was above.