2020-08-14 16:15:40 +02:00
|
|
|
import re
|
|
|
|
|
2020-08-14 15:53:42 +02:00
|
|
|
import markdown
|
2020-08-14 14:53:30 +02:00
|
|
|
from django.contrib.auth.models import AbstractUser
|
|
|
|
from django.db import models
|
2020-08-16 18:15:19 +02:00
|
|
|
from django.utils import timezone
|
2020-08-14 14:53:30 +02:00
|
|
|
|
|
|
|
|
|
|
|
class User(AbstractUser):
|
|
|
|
pass
|
2020-08-14 15:53:42 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Article(models.Model):
|
|
|
|
DRAFT = "draft"
|
|
|
|
PUBLISHED = "published"
|
|
|
|
STATUS_CHOICES = [
|
|
|
|
(DRAFT, "Draft"),
|
|
|
|
(PUBLISHED, "Published"),
|
|
|
|
]
|
|
|
|
title = models.CharField(max_length=255)
|
|
|
|
content = models.TextField()
|
|
|
|
status = models.CharField(max_length=15, choices=STATUS_CHOICES, default=DRAFT)
|
|
|
|
published_at = models.DateTimeField(null=True, blank=True)
|
|
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
|
|
updated_at = models.DateTimeField(auto_now=True)
|
|
|
|
author = models.ForeignKey(User, on_delete=models.PROTECT)
|
2020-08-14 22:06:38 +02:00
|
|
|
views_count = models.IntegerField(default=0)
|
2020-08-14 15:53:42 +02:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ["-published_at"]
|
|
|
|
|
2020-08-16 18:15:19 +02:00
|
|
|
def __str__(self):
|
|
|
|
return self.title
|
|
|
|
|
2020-08-14 15:53:42 +02:00
|
|
|
def get_abstract(self):
|
2020-08-14 16:15:40 +02:00
|
|
|
html = self.get_formatted_content()
|
2020-08-14 15:53:42 +02:00
|
|
|
return html.split("<!--more-->")[0]
|
|
|
|
|
|
|
|
def get_formatted_content(self):
|
|
|
|
md = markdown.Markdown(extensions=["extra"])
|
2020-08-14 16:15:40 +02:00
|
|
|
content = self.content
|
|
|
|
content = re.sub(r"(\s)#(\w+)", r"\1\#\2", content)
|
|
|
|
return md.convert(content)
|
2020-08-16 18:15:19 +02:00
|
|
|
|
2020-08-16 18:40:02 +02:00
|
|
|
def publish(self):
|
2020-08-16 18:15:19 +02:00
|
|
|
if not self.published_at:
|
|
|
|
self.published_at = timezone.now()
|
|
|
|
self.status = self.PUBLISHED
|
2020-08-16 18:40:02 +02:00
|
|
|
self.save()
|
2020-08-16 18:15:19 +02:00
|
|
|
|
2020-08-16 18:40:02 +02:00
|
|
|
def unpublish(self):
|
2020-08-16 18:15:19 +02:00
|
|
|
self.published_at = None
|
|
|
|
self.status = self.DRAFT
|
2020-08-16 18:40:02 +02:00
|
|
|
self.save()
|