from django.db import models # 导入内建的User模型 from django.contrib.auth.models import User # timezone用于处理时间相关的事物 from django.utils import timezone from django.urls import reverse from taggit.managers import TaggableManager from PIL import Image class ArticleColumn(models.Model): title = models.CharField(max_length=100, blank=True) created = models.DateTimeField(default=timezone.now) def __str__(self): return self.title # 博客文章数据模型 class ArticlePost(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) summary = models.CharField(max_length=100) body = models.TextField() tags = TaggableManager(blank=True) created = models.DateTimeField(default=timezone.now) # 使用timezone.now()时 进行数据迁移会,有警告 updated = models.DateTimeField(default=timezone.now) total_views = models.PositiveIntegerField(default=0) avatar = models.ImageField(upload_to='article/%Y%m%d/', blank=True) column = models.ForeignKey(ArticleColumn, null=True, blank=True, on_delete=models.CASCADE, related_name='article') class Meta: ordering = ('-created',) def __str__(self): return self.title def get_absolute_url(self): return reverse('article:article_detail', args=[self.id]) def save(self, *args, **kwargs): # 调用原有的save的功能 article = super(ArticlePost, self).save(*args, **kwargs) # 固定宽度缩放图片的大小 # if self.avatar and not kwargs.get('update_fields'): # image = Image.open(self.avatar) # (x, y) = image.size # new_x = 400 # new_y = int(new_x * (y / x)) # resized_image = image.resize((new_x, new_y), Image.ANTIALIAS) # resized_image.save(self.avatar.path) return article