Django Admin:如何同时保存页面和拆分标签?

时间:2012-11-16 10:09:40

标签: django django-admin

我正在尝试保存Page实例并同时拆分保存其标记。

这是我的代码:

class Page(models.Model):
    title = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, default='', blank=True)
    content = tinymce_models.HTMLField(blank=True)
    categories = models.ManyToManyField(PageCategory, related_name='page_categories', null=True, blank=True)
    tags = models.CharField(max_length=512, default='')

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        #save first
        self.slug = slugify(unidecode(self.title))
        obj = super(Page, self).save(*args, **kwargs) #save first
        if obj.id and obj.tags:  #split and assign tags to this page <--ERROR--
            tags = obj.tags.split(',')
            for t in tags:
                atag = t.strip(' ')
                tag, saved = Tag.objects.get_or_create(name=atag)
                obj.page_tags.add(tag)

class Tag(models.Model):
    name = models.CharField(max_length=255, unique=True)
    pages = models.ManyToManyField(Page, related_name='page_tags')

问题是我总是遇到这个错误: 'NoneType' object has no attribute 'id'

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该obj更改self

self.page_tags.add(tag)

因为model save() method don't return any data