CookBookCategoryDataModelPostMagic: models.py

File models.py, 1.4 KB (added by anonymous, 18 years ago)
Line 
1from django.db import models
2from django.core import validators
3
4# Begin Models here
5class Tag (models.Model):
6 name = models.CharField(core=True, maxlength=200)
7 slug = models.SlugField(prepopulate_from=('name',))
8 parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
9 description = models.TextField(blank=True,help_text="Optional")
10
11 class Admin:
12 list_display = ('name', '_parents_repr')
13
14 def __str__(self):
15 p_list = self._recurse_for_parents(self)
16 p_list.append(self.name)
17 return self.get_separator().join(p_list)
18
19 def get_absolute_url(self):
20 if self.parent_id:
21 return "/tag/%s/%s/" % (self.parent.slug, self.slug)
22 else:
23 return "/tag/%s/" % (self.slug)
24
25 def _recurse_for_parents(self, cat_obj):
26 p_list = []
27 if cat_obj.parent_id:
28 p = cat_obj.parent
29 p_list.append(p.name)
30 more = self._recurse_for_parents(p)
31 p_list.extend(more)
32 if cat_obj == self and p_list:
33 p_list.reverse()
34 return p_list
35
36 def get_separator(self):
37 return ' :: '
38
39 def _parents_repr(self):
40 p_list = self._recurse_for_parents(self)
41 return self.get_separator().join(p_list)
42 _parents_repr.short_description = "Tag parents"
43
44 def save(self):
45 p_list = self._recurse_for_parents(self)
46 if self.name in p_list:
47 raise validators.ValidationError("You must not save a category in itself!")
48 super(Tag, self).save()
49
50
Back to Top