提取元内容不起作用

Extract meta content doesn't work

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

这就是我所做的:

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)

但是卡片 class 的实例没有任何 self.title, self.description... 为什么??

这是因为您实际上还没有在模型中定义 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