E
E
ekzotika2020-06-22 12:27:49
Django
ekzotika, 2020-06-22 12:27:49

How to update Django model on change (override save method)?

The model has a "content" field. When changing this model, it is necessary to look for a symbol in the content field <aand add the line rel=nofollow to it (as if in a tag). I'm trying to make all this a function in the models.py file. Tell me how to do it?

The save function for this model:

def save(self, *args, **kwargs):
        if (self.original_price
                and not isinstance(self.original_price, Decimal)):
            self.original_price = Decimal(self.original_price)

        if self.parent_id is not None and self.parent_id == 0:
            self.parent = None

        # Если товар не доступен для заказа, то amount_europe и
        # amount_moscow считаем что не заданы
        if self.amount_free == 0:
            self.amount_europe = None
            self.amount_moscow = None

        if self._state.adding:
            self.sort_order = 0

        if self.content:
            self.content = self.content.replace('\n', '<br>')
            if '<a ' in self.content or '<iframe ' in self.content:
                self.content = re.sub(r'<.*?>', '', self.content,
                                      flags=re.IGNORECASE)

        # Устанавливаем цену для сортировки
        self.price_ordering = self.get_price()

        super().save(*args, **kwargs)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-06-22
@ekzotika

It's easiest to use sanitizer like https://pypi.org/project/html-sanitizer/ it has add_nofollow

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question