提取元内容不起作用

时间:2016-01-09 06:07:46

标签: django python-3.x preview

我想为我的网站建立一个类似电报预览的系统:

Telegram article preview

这就是我所做的:

class Card(models.Model):
    link = models.URLField('lien vers le post')

    def extract_meta(self):
        target = urlopen(self.link).read()
        tree = etree.HTML(target)
        metas = tree.xpath('//meta')

        self.title = None
        self.description = None
        self.image = None
        self.site_name = None

        for meta in metas:
            meta = etree.tostring(meta).decode('utf-8')
            if 'og:title' in meta:
                self.title = re.findall(r"content=\"(.*)\"", meta)[0]

            if 'og:description' in meta:
                self.description = re.findall(r"content=\"(.*)\"", meta)[0]

    def save(self, *args, **kwargs):
        self.extract_meta()
        super(Card, self).save(*args, **kwargs)

但是Card类的一个实例没有self.titleself.description ......为什么?

1 个答案:

答案 0 :(得分:0)

这是因为您尚未在模型中定义titledescription字段:

class Card(models.Model):
    link = models.URLField('lien vers le post')

    # add these two lines below
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)

当您添加了字段后,您就可以访问self.titleself.description