|
|
|
from django.db import models
|
|
|
|
from django.utils import timezone
|
|
|
|
from django.contrib.auth.models import User
|
|
|
|
from markdown import Markdown
|
|
|
|
|
|
|
|
|
|
|
|
class Category(models.Model):
|
|
|
|
"""文章分类"""
|
|
|
|
# 分类名称
|
|
|
|
title = models.CharField(max_length=100)
|
|
|
|
created = models.DateTimeField(default=timezone.now)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ['-created']
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.title
|
|
|
|
|
|
|
|
|
|
|
|
class Tag(models.Model):
|
|
|
|
"""文章标签"""
|
|
|
|
text = models.CharField(max_length=30)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
ordering = ['-id']
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.text
|
|
|
|
|
|
|
|
|
|
|
|
class Avatar(models.Model):
|
|
|
|
"""标题图"""
|
|
|
|
content = models.ImageField(upload_to='avatar/%Y%m%d')
|
|
|
|
|
|
|
|
|
|
|
|
# 博客文章 model
|
|
|
|
class Article(models.Model):
|
|
|
|
class Meta:
|
|
|
|
# 按创建时间降序排列
|
|
|
|
ordering = ['-created']
|
|
|
|
|
|
|
|
# 作者
|
|
|
|
author = models.ForeignKey(
|
|
|
|
User, # 父表
|
|
|
|
null=True,
|
|
|
|
on_delete=models.CASCADE,
|
|
|
|
# 一个作者可以对应多篇文章,作者是文章的一个外键
|
|
|
|
# 访问一个作者的所有文章可以用user.article_set.all()
|
|
|
|
# 也可以用到下面的related_name, user.articles.all(),和上面的语句作用相同
|
|
|
|
# 两者不能同时使用
|
|
|
|
related_name='articles'
|
|
|
|
)
|
|
|
|
|
|
|
|
# 分类
|
|
|
|
category = models.ForeignKey(
|
|
|
|
Category,
|
|
|
|
null=True,
|
|
|
|
blank=True,
|
|
|
|
on_delete=models.SET_NULL,
|
|
|
|
related_name='articles'
|
|
|
|
)
|
|
|
|
|
|
|
|
# 标签
|
|
|
|
# 一篇文章可以有多个tag,一个tag可以属于多篇文章
|
|
|
|
tags = models.ManyToManyField(
|
|
|
|
Tag,
|
|
|
|
blank=True,
|
|
|
|
related_name='articles',
|
|
|
|
)
|
|
|
|
|
|
|
|
# 标题图
|
|
|
|
avatar = models.ForeignKey(
|
|
|
|
Avatar,
|
|
|
|
null=True,
|
|
|
|
blank=True,
|
|
|
|
on_delete=models.SET_NULL,
|
|
|
|
related_name='article' # 这里是1对1关系
|
|
|
|
)
|
|
|
|
|
|
|
|
# 标题
|
|
|
|
title = models.CharField(max_length=100)
|
|
|
|
# 正文
|
|
|
|
body = models.TextField()
|
|
|
|
# 创建时间
|
|
|
|
created = models.DateTimeField(default=timezone.now)
|
|
|
|
# 更新时间
|
|
|
|
updated = models.DateTimeField(auto_now=True)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.title
|
|
|
|
|
|
|
|
# 新增方法,将body转换为带html标签的正文
|
|
|
|
def get_md(self):
|
|
|
|
md = Markdown(
|
|
|
|
extensions=[
|
|
|
|
'markdown.extensions.extra',
|
|
|
|
'markdown.extensions.codehilite',
|
|
|
|
'markdown.extensions.toc',
|
|
|
|
]
|
|
|
|
)
|
|
|
|
md_body = md.convert(self.body)
|
|
|
|
return md_body, md.toc
|
|
|
|
|
|
|
|
|
|
|
|
|