Friday, September 14, 2012

django-mptt form queryset filtering

Let's assume that we have a model called Category which is a subclass of MPTTModel. And we'd like to display a product creation form where user would choose a category among the category tree.


To achieve this, we have to use     category = TreeForeignKey(Category) in the Product model. This allows us to display the choice as a hierarchical tree.

class Product(models.Model):
    name = models.CharField(max_length=50)
    category = TreeForeignKey(Category)

class ProductForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super (ProductForm,self ).__init__(*args,**kwargs)
        self.fields['category'].queryset = Category.tree.filter(site=kwargs['instance'].site_id)

    class Meta:
        model = Product

When you want to filter the categories according to some criteria, you should use Category.tree.filter, not the usual way: Category.objects.filter.


Saturday, September 1, 2012

Missing mysql_config for MySQL-Django

If you want to use MySQL with django on Ubuntu/Mint, you have to
sudo apt-get install mysql-server libmysqlclient-dev
sudo pip install MySQL-python

libmysqlclient-dev ensures you have mysql_config executable. Otherwise MySQL-python connector won't be installed.