I have two models: products and catregories. A product can belong to
exactly one category. To make navigation easier, I use nested
categories. I want to limit the admin's ability to add a product only
to the leaf categories (those with no children). So if I the following
structure
Electronics > Mobile Phones > Nokia
Electronics > Cameras
The admin can add product to the Nokia or Cameras categories.
Here is the code for my models (I got the Category model from a link
on this list):
**************************************
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(core=True, maxlength=200)
slug = models.SlugField(prepopulate_from=('name',))
parent = models.ForeignKey('self', blank=True, null=True,
related_name='child')
description = models.TextField(blank=True,help_text="Optional")
class Admin:
list_display = ('name', '_parents_repr')
def __str__(self):
p_list = self._recurse_for_parents(self)
p_list.append(self.name)
return self.get_separator().join(p_list)
def __unicode__(self):
p_list = self._recurse_for_parents(self)
p_list.append(self.name)
return self.get_separator().join(p_list)
def get_absolute_url(self):
if self.parent_id:
return "/tag/%s/%s/" % (self.parent.slug, self.slug)
else:
return "/tag/%s/" % (self.slug)
def _recurse_for_parents(self, cat_obj):
p_list = []
if cat_obj.parent_id:
p = cat_obj.parent
p_list.append(p.name)
more = self._recurse_for_parents(p)
p_list.extend(more)
if cat_obj == self and p_list:
p_list.reverse()
return p_list
def get_separator(self):
return ' :: '
def _parents_repr(self):
p_list = self._recurse_for_parents(self)
return self.get_separator().join(p_list)
_parents_repr.short_description = "Tag parents"
def save(self):
p_list = self._recurse_for_parents(self)
if self.name in p_list:
raise validators.ValidationError("You must not save a
category in
itself!")
super(Category, self).save()
class product(models.Model):
name = models.CharField(core=True, maxlength=200)
slug = models.SlugField(prepopulate_from=('name',))
category = models.ForeignKey(Category, related_name='product
category')
description = models.TextField(blank=True,help_text="Optional")
class Admin:
list_display = ('name', 'category')
def __str__(self):
return self.name
*****************************
I really appreciate the help!
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---