Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Self-referencing many-to-many through
How to implement self-referencing many-to-many relationships in Django. Example use cases are modeling asymmetrical following (a-la twitter) or symmetrical friendship (a-la facebook). -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Django render_to_response
It is important to see how django doesn’t automatically appends the context variables to the request object. Say you want to access MEDIA_URL in your templates, using the following code will not work since the context is not created and it is not passed to the render_to_response function def my_view(request): return render_to_response('my_template.html', my_data_dictionary) The first [...] -
FireLogger per Python
Quan hom fa feina amb Django una de les primeres coses que aprèn és a mirar la consola del servidor de desenvolupament. Al la consola hi apareixen els missatges d'error i els logs bé en forma de prints o com a logs de Python. Convé evitar fer prints i fer servir els logs. Aprofitarem el funcionament del logger per tal de discrimitar els tipus de log i distingir entre els missatges que volem que es mostrin sols en depuració (DEBUG), errors o informatious. Una configuració molt bàsica del logs és la que propòs a projecte base d'appfusedjango, molt ràpidament: Al properties.py o al settings configuram el sistema de log 1 2 3 4 5import logging logging.basicConfig( format="%(asctime)s-%(levelname)s-%(name)s-%(lineno)s-%(message)s", level = logging.DEBUG, ) i a cada arxiu on el volguem fer servir 1 2import logging log = logging.getLogger(__name__) Això ens permte configurar a un sols lloc el nivell de log que volguem i a més saber des d'on s'estan generant els missatges. Com a retruc, a més ens servirà per poder mostrar els logs a la consola del Firebug gràcies a l'aplicació FireLogger. Aquesta aplicació té una instal·lació en dues parts, ja que hem d'instal·lar el plugin de Firefox que hi trobareu … -
Migrating to Django Mingus
I've migrated my blog from a creaking Plone 2.5 to a fork of Django Mingus. This is the process I went through. -
Migrating to Django Mingus
I've been running a blog since 2007 (check the archives!). At the time, it made most sense for me to go for a Plone-based blog. Plone was what I was most familiar with, and there was a simple blog product out there that I could use called, sensibly enough, SimpleBlog. In fact, you can still grab it - it's where you'd expect on the Plone Products section. And as you can see, the release there was the one that I used at the time - SimpleBlog 2.0, for Plone 2.5 Fast-forward to the start of 2010, and things have moved on. Plone's moved on, for sure. Plone 4 is just around the corner, and there's some really, really cool stuff in there: Dexterity, a new content types framework, finally looks like it'll make content type creation as easy as it should be, and simple types and behaviours can be created through the web. Deco, slated (last time I heard) for Plone 5, is quite literally going to make publishers wet themselves. And Deliverance has got great potential in helping to unify the many disparate systems which makes the typical corporate user's daily life such a grind. Thing is, I'm not … -
Migrating to Django Mingus
I've been running a blog since 2007 (check the archives!). At the time, it made most sense for me to go for a Plone-based blog. Plone was what I was most familiar with, and there was a simple blog product out there that I could use called, sensibly enough, SimpleBlog. In fact, you can still grab it - it's where you'd expect on the Plone Products section. And as you can see, the release there was the one that I used at the time - SimpleBlog 2.0, for Plone 2.5 Fast-forward to the start of 2010, and things have moved on. Plone's moved on, for sure. Plone 4 is just around the corner, and there's some really, really cool stuff in there: Dexterity, a new content types framework, finally looks like it'll make content type creation as easy as it should be, and simple types and behaviours can be created through the web. Deco, slated (last time I heard) for Plone 5, is quite literally going to make publishers wet themselves. And Deliverance has got great potential in helping to unify the many disparate systems which makes the typical corporate user's daily life such a grind. Thing is, I'm not … -
Migrating to Django Mingus
I've been running a blog since 2007 (check the archives!). At the time, it made most sense for me to go for a Plone-based blog. Plone was what I was most familiar with, and there was a simple blog product out there that I could use called, sensibly enough, SimpleBlog. In fact, you can still grab it - it's where you'd expect on the Plone Products section. And as you can see, the release there was the one that I used at the time - SimpleBlog 2.0, for Plone 2.5 Fast-forward to the start of 2010, and things have moved on. Plone's moved on, for sure. Plone 4 is just around the corner, and there's some really, really cool stuff in there: Dexterity, a new content types framework, finally looks like it'll make content type creation as easy as it should be, and simple types and behaviours can be created through the web. Deco, slated (last time I heard) for Plone 5, is quite literally going to make publishers wet themselves. And Deliverance has got great potential in helping to unify the many disparate systems which makes the typical corporate user's daily life such a grind. Thing is, I'm not … -
jQuery 1.4 Released
Many (awesome) changes http://blog.jquery.com/2010/01/14/jquery-14-released/. View the release notes here: http://jquery14.com/day-01/jquery-14 Related posts:jQuery 1.4.2 Released jQuery 1.4 Alpha 1 Released jQuery 1.4a2 (Alpha 2) Released Related posts:jQuery 1.4.2 Released jQuery 1.4 Alpha 1 Released jQuery 1.4a2 (Alpha 2) Released -
For the Love of Ponies
For the Love of Ponies. Bryan Veloso, the discoverer of the Django Pony, makes contact with the artist who released the original drawing on iStockPhoto. -
Doing things with Django forms
Forms are one of the best features of Django. (After models, admin, url routing etc ). Here is a quick tutorial describing how to do things with Django forms. Basic form Prob. You want to show a form, validate it and display it. Ans. Create a simple form. class UserForm(forms.Form): username = forms.CharField() joined_on = [...] Related posts:Dynamic forms with Django Five Things I Hate About Django. Develop Twitter API application in django and deploy on Google App Engine -
Django: Highlighting with ReST using Pygments
In my last post I wrote about code highlighting in HTML formatted text, but since I’m now using reStructuredText for markup things, I want to share how I added synthax highlighting for this. Within your project directory (the same that contains the settings.py) create a file called rst_directive.py and fill it with the following code: # -*- coding: utf-8 -*- """ The Pygments reStructuredText directive ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This fragment is a Docutils_ 0.5 directive that renders source code (to HTML only, currently) via Pygments. To use it, adjust the options below and copy the code into a module that you import on initialization. The code then automatically registers a ``sourcecode`` directive that you can use instead of normal code blocks like this:: .. sourcecode:: python My code goes here. If you want to have different code styles, e.g. one with line numbers and one without, add formatters with their names in the VARIANTS dict below. You can invoke them instead of the DEFAULT one by using a directive option:: .. sourcecode:: python :linenos: My code goes here. Look at the `directive documentation`_ to get all the gory details. .. _Docutils: http://docutils.sf.net/ .. _directive documentation: http://docutils.sourceforge.net/docs/howto/rst-directives.html :copyright: Copyright 2006-2009 by the Pygments … -
Django: Highlighting with ReST using Pygments
In my last post I wrote about code highlighting in HTML formatted text, but since I’m now using reStructuredText for markup things, I want to share how I added synthax highlighting for this. Within your project directory (the same that contains the settings.py) create a file called rst_directive.py and fill it with the following code: # -*- coding: utf-8 -*- """ The Pygments reStructuredText directive ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This fragment is a Docutils_ 0.5 directive that renders source code (to HTML only, currently) via Pygments. To use it, adjust the options below and copy the code into a module that you import on initialization. The code then automatically registers a ``sourcecode`` directive that you can use instead of normal code blocks like this:: .. sourcecode:: python My code goes here. If you want to have different code styles, e.g. one with line numbers and one without, add formatters with their names in the VARIANTS dict below. You can invoke them instead of the DEFAULT one by using a directive option:: .. sourcecode:: python :linenos: My code goes here. Look at the `directive documentation`_ to get all the gory details. .. _Docutils: http://docutils.sf.net/ .. _directive documentation: http://docutils.sourceforge.net/docs/howto/rst-directives.html :copyright: Copyright 2006-2009 by the Pygments … -
Django: Highlighting in HTML using Pygments and Beautiful Soup
Two months ago I wrote about Django, Pygments and Beautiful Soup. A few days after the post I switched from HTML markup to reStructuredText and thus didn’t need my filter anymore and forgot to post more about it. Today I received a comment asking me to publish the source code of the template filter—so here it is: # encoding: utf-8 """ A filter to highlight code blocks in html with Pygments and BeautifulSoup. {% load highlight_code %} {{ var_with_code|highlight|safe }} """ from BeautifulSoup import BeautifulSoup from django import template from django.template.defaultfilters import stringfilter import pygments import pygments.formatters import pygments.lexers register = template.Library() @register.filter @stringfilter def highlight(html): soup = BeautifulSoup(html) codeblocks = soup.findAll('pre') for block in codeblocks: if block.has_key('class'): try: code = ''.join([unicode(item) for item in block.contents]) lexer = pygments.lexers.get_lexer_by_name(block['class']) formatter = pygments.formatters.HtmlFormatter() code_hl = pygments.highlight(code, lexer, formatter) block.contents = [BeautifulSoup(code_hl)] block.name = 'code' except: raise return unicode(soup) Copy the code into a file called templatetags/highlight_code.py within a new or an existing Django app. highlight() searches the passed HTML code for <pre>-tags with a class denoting the lexer to be used, e.g.: <p><em>Hello World!</em> in Python:</p> <pre class="python"> print 'Hello World' </pre> Furthermore you might want to create a CSS file … -
Django: Highlighting in HTML using Pygments and Beautiful Soup
Two months ago I wrote about Django, Pygments and Beautiful Soup. A few days after the post I switched from HTML markup to reStructuredText and thus didn’t need my filter anymore and forgot to post more about it. Today I received a comment asking me to publish the source code of the template filter—so here it is: # encoding: utf-8 """ A filter to highlight code blocks in html with Pygments and BeautifulSoup. {% load highlight_code %} {{ var_with_code|highlight|safe }} """ from BeautifulSoup import BeautifulSoup from django import template from django.template.defaultfilters import stringfilter import pygments import pygments.formatters import pygments.lexers register = template.Library() @register.filter @stringfilter def highlight(html): soup = BeautifulSoup(html) codeblocks = soup.findAll('pre') for block in codeblocks: if block.has_key('class'): try: code = ''.join([unicode(item) for item in block.contents]) lexer = pygments.lexers.get_lexer_by_name(block['class']) formatter = pygments.formatters.HtmlFormatter() code_hl = pygments.highlight(code, lexer, formatter) block.contents = [BeautifulSoup(code_hl)] block.name = 'code' except: raise return unicode(soup) Copy the code into a file called templatetags/highlight_code.py within a new or an existing Django app. highlight() searches the passed HTML code for <pre>-tags with a class denoting the lexer to be used, e.g.: <p><em>Hello World!</em> in Python:</p> <pre class="python"> print 'Hello World' </pre> Furthermore you might want to create a CSS file … -
Developing Reusable Django Apps
Django app structure is an implementation of seperation of concerns. It is slightly different than what you can find in other MVC frameworks. The stack is split vertically, not horizontally. And then the app is split horizontally within, i.e. models, views, templates etc are in their seperate modules/packages/directories. This vertical splitting allows you to collect [...] -
Native Django on App Engine
Update 3: This post is outdated. Please read the djangoappengine documentation. Update 2: Please read the djangoappengine documentation instead of this post for detailed installation instructions. The "common-apps" folder has been deprecated. Just put all dependencies directly into your project folder. The "djangotoolbox" repository folder structure has changed a little bit. The link to "djangotoolbox" should now point to the "djangotoolbox/djangotoolbox" subfolder instead of the repository itself. Also, the App Engine backend now supports IN and != queries and DecimalField. Update: We've updated the installation instructions. You now also need djangotoolbox. Additionally, a simplified version of this post has been added to the documentation section of djangoappengine. About a few months ago we started to port Django to support non-relational databases and to implement an App Engine database backend for this port. So far we ended up supporting basic Django functionality on App Engine. This post is intended to get you started using our port and to let you know what you can do and want you can't do with it at the moment. So let's start! Installation In order to use our port on App Engine you have to clone a few repositories first. These are the django-nonrel repository, … -
Django Documentation iPhone app updated
A new version of the Django documentation iPhone app has been pushed to iTunes. Updates are: Updated to 1.2 alpha 1 documentation App now remembers the page you were last on and re-opens it at the start. Code samples when page is rotated widen. Some copyright notices added. -
Django patterns, part 2: efficient reverse lookups
One of the main sources of unnecessary database queries in Django applications is reverse relations. By default, Django doesn't do anything to follow relations across models. This means that unless you're careful, any relationship can lead to extra hits on the database. For instance, assuming MyModel has a ForeignKey to MyRelatedModel, this: myobj = MyModel.objects.get(pk=1) print myobj.myrelatedmodel.name hits the database two separate times - once to get the MyModel object, and once to get the related MyRelatedModel object. Luckily, it's easy to get Django to optimise this into a single call: myobj = MyModel.objects.select_related.get(pk=1) This way Django does a JOIN in the database call, and caches the related object in a hidden attribute of myobj. Printing myobj.__dict__ will show this: {'_myrelatedmodel_cache': [MyRelatedModel: obj], 'name': 'My name'} Now, whenever you call myobj.myrelatedmodel, Django automatically uses the version in _myrelatedmodel_cache rather than going back to the database to get it. Note that this is exactly the same as what happens once the the related object was accessed in the first snippet above - Django caches it in the same way for future use. All select_related() does is pre-cache it before the first access. None of this is new - it's quite well … -
Looking at registration patterns in Django
Django uses several types of registration patterns for some of its most notable features. This entry looks at the way django implements its different types of registries. -
Looking at registration patterns in Django
Most developers who have written a Django application are familiar with the admin interface. In this post I'll talk about the way the admin module uses a registration pattern to allow tools like admin.autodiscover() and admin.site.urls to do their magic. Registration patterns are useful when developing flexible and extensible libraries. By specifying an interface and allowing you to register your custom implementations, the library code remains decoupled from your own custom code. To get an idea of how these patterns work, let's take a look at the django.contrib.admin.sites module, we find a class called AdminSite which is instantiated at the bottom of the file (essentially a singleton that is used by default across your apps). The first lines of the __init__ method reveal that at the heart of this class, there's an attribute called _registry, which is a dictionary of Model classes and ModelAdmin instances. def __init__(self, name=None, app_name='admin'): self._registry = {} # model_class class -> admin_class instance When we import admin and run admin.site.register(), the register method on AdminSite is called, which performs some validation and then adds the model/modeladmin to its internal dictionary: # Instantiate the admin class to save in the registry self._registry[model] = admin_class(model, self) When … -
Looking at registration patterns in Django
Most developers who have written a Django application are familiar with the admin interface. In this post I'll talk about the way the admin module uses a registration pattern to allow tools like admin.autodiscover() and admin.site.urls to do their magic. Registration patterns are useful when developing flexible and extensible libraries. By specifying an interface and allowing you to register your custom implementations, the library code remains decoupled from your own custom code. To get an idea of how these patterns work, let's take a look at the django.contrib.admin.sites module, we find a class called AdminSite which is instantiated at the bottom of the file (essentially a singleton that is used by default across your apps). The first lines of the __init__ method reveal that at the heart of this class, there's an attribute called _registry, which is a dictionary of Model classes and ModelAdmin instances. def __init__(self, name=None, app_name='admin'): self._registry = {} # model_class class -> admin_class instance When we import admin and run admin.site.register(), the register method on AdminSite is called, which performs some validation and then adds the model/modeladmin to its internal dictionary: # Instantiate the admin class to save in the registry self._registry[model] = admin_class(model, self) When …