博客开发日志系统

创建新的表和model:

class Timeline(models.Model):
    SIDE_CHOICE = (
        ('L', '左边'),
        ('R', '右边'),
    )

    side = models.CharField(
        '位置', max_length=1, choices=SIDE_CHOICE, default='L')
    icon = models.CharField('图标', max_length=50, default='fa fa-pencil')
    title = models.CharField('标题', max_length=100)
    update_date = models.DateTimeField('更新时间')
    content = models.TextField('主要内容')
    slug = models.SlugField(editable=False,null=True, unique=True)
    class Meta:
        verbose_name = '博客升级时间线'
        verbose_name_plural = verbose_name
        ordering = ['update_date']

    def __str__(self):
        return self.title[:20]

    def get_timeline_list(self):
        """返回所有文章列表"""
        return Timeline.objects.all()

    def title_to_emoji(self):
        return emoji.emojize(self.title, use_aliases=True)

    def content_to_markdown(self):
        # 先转换成emoji然后转换成markdown
        to_emoji_content = emoji.emojize(self.content, use_aliases=True)
        return markdown.markdown(to_emoji_content,
                                 extensions=['markdown.extensions.extra', ]
                                 )

    def save(self, *args, **kwargs):
            self.slug = slugify(self.title)
            super(Timeline, self).save(*args, **kwargs)

生成python_web的类的文章的时候自动生成并添加到开发日志中

为了方便管理网站,我们希望以后每次创建python_web类的文章的时候就直接添加到开发日志中,具体代码在73行

class Article(models.Model):
    # 文章默认缩略图
    IMG_LINK = '/static/images/summary.jpg'
    # 文章作者
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='作者', null=False, default='2')
    title = models.CharField(max_length=150, verbose_name='文章标题')
    summary = MDTextField(
        '文章摘要', max_length=230, default='文章摘要等同于网页description内容,请务必填写...')
    # 文章内容
    body = MDTextField(verbose_name='文章内容')
    img_link = models.CharField('图片地址', default=IMG_LINK, max_length=255)
    create_date = models.DateTimeField(verbose_name='创建时间')
    update_date = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    views = models.IntegerField('阅览量', default=0)
    img = models.ImageField(upload_to='media/article',
                            default='media/artile/default.png', storage=ImageStorage())
    # img_bmp= ImageSpecField(
    #     source="img",
    #     # processors=[ResizeToFill(240,130)],  # 处理后的图像大小
    #     format='png',  # 处理后的图片格式
    #     options={'quality': 80}  # 处理后的图片质量
    # )
    # 文章唯一标识符
    slug = models.SlugField(editable=False)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, verbose_name='文章分类', null=False, default='2')
    keywords = models.ManyToManyField(Keyword, verbose_name='文章关键词',
                                      help_text='文章关键词,用来作为SEO中keywords,最好使用长尾词,3-4个足够')

    #置顶
    is_top = models.BooleanField('是否首页展示', default=False)
    #是否更新timeline
    is_addtimeline = models.BooleanField('是否添加时间线', default=False)
    class Meta:
        verbose_name = '文章'
        verbose_name_plural = verbose_name
        ordering = ['-create_date']

    def __str__(self):
        return self.title[:20]

    def get_absolute_url(self):
        return reverse('blog:article', kwargs={'slug': self.slug})

    def body_to_markdown(self):
        return markdown.markdown(self.body, extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
        ])

    def summary_to_markdown(self):
        return markdown.markdown(self.summary, extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
        ])

    def update_views(self):
        self.views += 1
        self.save(update_fields=['views'])

    def get_num(self):
        return Article.objects.filter(id__lt=self.id).count()

    def get_pre(self):
        return Article.objects.filter(id__lt=self.id).order_by('-id').first()

    def get_next(self):
        return Article.objects.filter(id__gt=self.id).order_by('id').first()

    #添加到博客开发时间线
    def add_time(self):
        web_time = Timeline()
        web_time.title = self.title
        web_time.content = self.summary
        web_time.icon = self.img
        web_time.update_date = self.create_date
        web_time.save()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)  # 讲中文title变成拼音。
        #在添加文章时手动选择是否添加到开发日志
        if(self.is_addtimeline):
            try:
                #如何只是对文章进行修改,说明已经添加过
                if(Timeline.objects.get(slug=self.slug)):
                    #则只对日志中的内容和图片和时间进行修改。
                    old = Timeline.objects.get(slug=self.slug)
                    old.content = self.summary
                    old.icon = self.img
                    old.update_date = self.create_date
                    old.save(update_fields=['content', 'icon','update_date'])
                else:
                    #如果没有添加过则就直接创建日志再发布
                    self.add_time()
                    #objects.get可能的报错
            except Timeline.DoesNotExist:
                self.add_time()
            except Timeline.MultipleObjectsReturned:
                pass
        super(Article, self).save(*args, **kwargs)

原创文章,转载请注明出处:https://boywithacoin.cn/article/djangobo-ke-kai-fa-blogkai-fa-ri-zhi-xi-tong/