from django.core.management.base import BaseCommand

from news.models import News
import re

class Command(BaseCommand):
    help = 'Removes empty img html tags from news description'

    relative_img_regex = re.compile(r'\<img.+src=(?!https?:\/\/)([^\/].+?)[\"|\']>', re.I)

    def handle(self, *args, **kwargs):
        for news in News.objects.all():
            if isinstance(news.description, dict):
                news.description = {locale: self.relative_img_regex.sub('', rich_text)
                                    for locale, rich_text in news.description.items()}
                self.stdout.write(self.style.WARNING(f'Replaced {news} empty img html tags...\n'))
                news.save()