def save(self, *args, **kwargs):
self.content = b64_to_file(self.content)
super(Entry, self).save(*args, **kwargs)
def b64_to_file(content):
try:
mat = re.findall(r'src="([^"]+)"',content)
for x in mat:
imgData = x.split(',', maxsplit=1)[1]
ImgGUID = str(uuid.uuid4())
imgSaveURL = settings.STATICFILES_DIRS[1] + '/img/entry/' + ImgGUID + '.png'
imgURL = '/static/img/entry/' + ImgGUID + '.png'
try:
with open(imgSaveURL, "wb") as fh:
fh.write(base64.decodestring(imgData.encode()))
content = content.replace(x, imgURL)
except:
pass
except:
return content
return content
class Entry(models.Model):
LIVE_STATUS = 1
DRAFT_STATUS = 2
STATUS_CHOICES = (
(LIVE_STATUS, 'Отображается'),
(DRAFT_STATUS, 'Черновик'),
)
author = models.ForeignKey(User, verbose_name='Автор')
categories = models.ManyToManyField('Category', verbose_name='Категория')
image = models.ForeignKey(Image)
title = models.CharField(max_length=255, help_text='Максимум 255 символов.', verbose_name='Название новости')
slug = models.SlugField(unique_for_date='pub_date', help_text='Только английские буквы и дефисы.', verbose_name='Ссылка')
excerpt = models.TextField(max_length=200, help_text='Максимум 200 символов.', verbose_name='Краткий текст новости')
content = tinymce_models.HTMLField(help_text='Полный текст новости', verbose_name='Полный текст новости')
pub_date = models.DateTimeField(default=datetime.datetime.now, verbose_name='Дата публикации')
featured = models.BooleanField(default=False, verbose_name='Избранная новость')
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS, verbose_name='Статус')
hits = models.IntegerField(default=0, editable=False)
objects = EntryQuerySet.as_manager()
def add_hits(self):
if self.hits is not None:
self.hits += 1
self.save()
else:
self.hits = 0
class Meta:
ordering = ['-pub_date']
verbose_name_plural = 'Новости'
verbose_name = 'Новость'
def __str__(self):
return self.title
class EntryAdmin(admin.ModelAdmin):
fieldsets = (
('Блок 1', {
'fields': ('author', 'categories', 'image', 'title')
}),
('Блок 2', {
'fields': ('slug', 'excerpt', 'content', 'pub_date', 'featured', 'status', 'hits', 'objects'),
}),
)
<code>