0 votes
in Programming by (400 points)

I have a function in my models.py that adds the news I pass to it via a URL using OpenGraph. This process works fine, but there are some websites that give me an error, how can I use a try except to control this error and the application does not crash?

When the error occurs, I would like the application in the admin panel to return me to the same place where it was before, but indicating the error.

Best regards and thank you very much!

My models.py:

class Post(models.Model):
title = models.CharField(max_length=200, verbose_name="Título", null=True, blank=True)
content = RichTextField(verbose_name="Contenido", null=True, blank=True)
published = models.DateTimeField(verbose_name="Fecha de publicación", default=now, null=True, blank=True)
image = models.ImageField(verbose_name="Imagen", upload_to="blog", null=True, blank=True)
author = models.ForeignKey(UserManegement, verbose_name="Autor", on_delete=models.CASCADE)
categories = models.ManyToManyField(Category, verbose_name="Categorias", related_name="get_posts")
url_web = models.URLField(verbose_name="URL", null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creacion')
updated = models.DateTimeField(auto_now=True, verbose_name='Fecha de ediccion')

class Meta:
    verbose_name = "entrada"
    verbose_name_plural = "entradas"
    ordering = ['-created']

def __str__(self):
    return self.title

The function in which I want to insert the try except. It is in the same models.py:

@receiver(pre_save, sender=Post)
def url_processor(sender, instance, *args, **kwargs):

    if instance.url_web:

        title, description, image = web_preview(instance.url_web)

        instance.title = title
        instance.content = description
        path = 'blog/' + uuid.uuid4().hex + '.png'
        instance.image = path
        img_data = requests.get(image).content
        with open('media/' + path, 'wb') as handler:

Please log in or register to answer this question.