0

我想根据website下面的字段填充一些字段。我将网站作为参数发送到 API,它以 JSON 格式返回多个值。然后我想发送它并将其存储在该实例的模型中。

class newURLposts(models.Model):
    created_on = models.DateTimeField(auto_now_add=True)
    website = models.URLField(max_length=250)   
    domain = models.TextField(blank=True)
    host = models.TextField(blank=True)
    url = models.URLField(blank=True)
    img = models.ImageField(upload_to='link/img/',blank=True)
    title = models.TextField(blank=True)
    description =  models.TextField(blank=True)
    favicon = models.ImageField(upload_to='link/favicon/',blank=True)

    def save(self, *args, **kwargs):
        review_url = self.website
        u = "u=" + review_url
        r = "&r=#####"
        e = "&e=#####"
        t = "&t=json"
        PARAMS12 = u + r + e + t
        URL = "#####"

        site = requests.get(url = URL, params = PARAMS12)
        parsed_site = json.loads(site.content.decode('utf-8'))


        self.domain = parsed_site["domain"]
        self.host = parsed_site["host"]
        self.url = parsed_site["url"]
        self.img = parsed_site["img"]
        self.title = parsed_site["title"]
        self.description = parsed_site["description"]
        self.favicon = parsed_site["favicon"]
        super().save(*args, **kwargs)

    class Meta:
        ordering = ['-created_on']
4

1 回答 1

0

解决了问题 - 把它分成两个肉棒

class newURLposts(models.Model):
    created_on = models.DateTimeField(auto_now_add=True)
    website= models.URLField(max_length=250)

    #Info from gutURL
    domain = models.TextField(blank=True)
    host = models.TextField(blank=True)
    url = models.URLField(blank=True)
    img = models.ImageField(upload_to='link/img/',blank=True)
    title = models.TextField(blank=True)
    description =  models.TextField(blank=True)
    favicon = models.ImageField(upload_to='link/favicon/',blank=True)

    def parsed_site(self, *args, **kwargs):
        review_url = self.website
        u = "u=" + review_url
        r = "&r=####"
        e = "&e=####"
        t = "&t=json"
        PARAMS12 = u + r + e + t
        URL = "####"

        site = requests.get(url = URL, params = PARAMS12)
        return json.loads(site.content.decode('utf-8'))

    def save(self, *args, **kwargs):
        self.domain = self.parsed_site()["domain"]
        self.host = self.parsed_site()["host"]
        self.url = self.parsed_site()["url"]
        self.img = self.parsed_site()["img"]
        self.title = self.parsed_site()["title"]
        self.description = self.parsed_site()["description"]
        self.favicon = self.parsed_site()["favicon"]
        super(newURLposts, self).save(*args, **kwargs)

    class Meta:
        ordering = ['-created_on']
于 2020-01-13T15:40:32.253 回答