models.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from django.db import models
  2. # 导入内建的User模型
  3. from django.contrib.auth.models import User
  4. # timezone用于处理时间相关的事物
  5. from django.utils import timezone
  6. from django.urls import reverse
  7. from taggit.managers import TaggableManager
  8. from PIL import Image
  9. class ArticleColumn(models.Model):
  10. title = models.CharField(max_length=100, blank=True)
  11. created = models.DateTimeField(default=timezone.now)
  12. def __str__(self):
  13. return self.title
  14. # 博客文章数据模型
  15. class ArticlePost(models.Model):
  16. author = models.ForeignKey(User, on_delete=models.CASCADE)
  17. title = models.CharField(max_length=100)
  18. summary = models.CharField(max_length=100)
  19. body = models.TextField()
  20. tags = TaggableManager(blank=True)
  21. created = models.DateTimeField(default=timezone.now) # 使用timezone.now()时 进行数据迁移会,有警告
  22. updated = models.DateTimeField(default=timezone.now)
  23. total_views = models.PositiveIntegerField(default=0)
  24. avatar = models.ImageField(upload_to='article/%Y%m%d/', blank=True)
  25. column = models.ForeignKey(ArticleColumn,
  26. null=True,
  27. blank=True,
  28. on_delete=models.CASCADE,
  29. related_name='article')
  30. class Meta:
  31. ordering = ('-created',)
  32. def __str__(self):
  33. return self.title
  34. def get_absolute_url(self):
  35. return reverse('article:article_detail', args=[self.id])
  36. def save(self, *args, **kwargs):
  37. # 调用原有的save的功能
  38. article = super(ArticlePost, self).save(*args, **kwargs)
  39. # 固定宽度缩放图片的大小
  40. # if self.avatar and not kwargs.get('update_fields'):
  41. # image = Image.open(self.avatar)
  42. # (x, y) = image.size
  43. # new_x = 400
  44. # new_y = int(new_x * (y / x))
  45. # resized_image = image.resize((new_x, new_y), Image.ANTIALIAS)
  46. # resized_image.save(self.avatar.path)
  47. return article