class UserCourse(BaseModel): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name="用户") course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name="课程") image = StdImageField(max_length=100, upload_to=UploadToUUID(path=datetime.now().strftime('course/user_course/%Y/%m')), verbose_name=u"课程封面", variations={'thumbnail': {'width': 100, 'height': 75}}) class Meta: verbose_name = "用户课程" verbose_name_plural = verbose_name def __str__(self): return self.course.name def show_image(self): if self.image: href = self.image.url # 点击后显示的放大图片 src = self.image.thumbnail.url # 页面显示的缩略图 # 插入html代码 image_html = '<a href="%s" target="_blank" title="传图片"><img alt="" src="%s"/>' % (href, src) return image_html else: return u'上传图片' show_image.short_description = "课程封面" show_image.allow_tags = True
class New(models.Model): title = models.CharField(max_length=80) title_rom = models.CharField(max_length=80) content = models.TextField() content_rom = models.TextField() slug = models.SlugField(blank=True) image = StdImageField(upload_to=UploadToUUID(path=''), blank=True, variations={ 'thumbnail': (300, 300, True), }) date = models.DateTimeField(default=timezone.now) published = models.BooleanField(default=True) TYPES = ((1, 'High'), (0, 'Low')) priority = models.IntegerField(choices=TYPES, null=False, default=1) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) audio = models.CharField(max_length=80, blank=True) audio_rom = models.CharField(max_length=80, blank=True) def __str__(self): return '{} - {}'.format(self.category, self.title) def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.title) tts = gTTS(text=self.content, lang='ru') tts_rom = gTTS(text=self.content_rom, lang='ro') tts.save(settings.MEDIA_ROOT + '/' + self.slug + '.mp3') tts_rom.save(settings.MEDIA_ROOT + '/' + self.slug + '_rom.mp3') self.audio = settings.MEDIA_URL + self.slug + '.mp3' self.audio_rom = settings.MEDIA_URL + self.slug + '_rom.mp3' super(New, self).save(*args, **kwargs)
class UserProfile(models.Model): user = models.OneToOneField('accounts.User', on_delete=models.CASCADE) avatar = StdImageField( upload_to=UploadToUUID(path='avatars'), default='avatars/default_avatar.png', variations={ # "width", "height", "crop" 'large': (150, 150, False), 'thumbnail': (80, 80, False) }, render_variations=image_processor) class Meta: verbose_name = 'User profile' verbose_name_plural = 'User profiles' def __str__(self): return f'userprofile: {self.user.username}' @property def accounts(self): """ :return: User's active games accounts """ account_names = [cls.__name__ for cls in GameAccount.__subclasses__()] accounts = { acc_name: getattr(self, f'{acc_name.lower()}_set').all() for acc_name in account_names } return accounts
class Banner(BaseModel): title = models.CharField(max_length=100, verbose_name="标题") image = StdImageField(max_length=200, upload_to=UploadToUUID(path=datetime.now().strftime('banner/%Y/%m')), verbose_name=u"轮播图", variations={'thumbnail': {'width': 100, 'height': 75}}) url = models.URLField(max_length=200, verbose_name="访问地址") index = models.IntegerField(default=0, verbose_name="顺序") class Meta: verbose_name = "轮播图" verbose_name_plural = verbose_name def __str__(self): return self.title def show_image(self): if self.image: href = self.image.url # 点击后显示的放大图片 src = self.image.thumbnail.url # 页面显示的缩略图 # 插入html代码 image_html = '<a href="%s" target="_blank" title="传图片"><img alt="" src="%s"/>' % (href, src) return image_html else: return u'上传图片' show_image.short_description = "轮播图" show_image.allow_tags = True
class Banner(models.Model): title = models.CharField(max_length=100, verbose_name=u"标题") # image = models.ImageField(upload_to="banner/%Y/%m", verbose_name=u"轮播图", max_length=100) image = StdImageField(max_length=100, upload_to=UploadToUUID(path=datetime.now().strftime('banner/%Y/%m')), verbose_name=u"轮播图", variations={'thumbnail': {'width': 100, 'height': 75}}) url = models.URLField(max_length=200, verbose_name=u"访问地址") index = models.IntegerField(default=0, verbose_name=u"顺序") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = u"轮播图" verbose_name_plural = verbose_name def image_img(self): if self.image: return str('<img src="%s" />' % self.image.thumbnail.url) else: return u'上传图片' image_img.short_description = '轮播图' image_img.allow_tags = True def __str__(self): return '{0}(位于第{1}位)'.format(self.title, self.index)
class GIFEntry(TimeStampedModel): title = models.CharField( _('title'), max_length=255, ) gif_file = StdImageField( upload_to=UploadToUUID(path='gifs'), validators=[ validate_gif_file_extension, ], ) author = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('author'), related_name='gif_entries', on_delete=models.CASCADE, ) tags = TaggableManager(blank=True) class Meta: verbose_name = _('gif entry') verbose_name_plural = _('gif entries') def __str__(self): return self.title
class Strategy(models.Model): state = (('review', '审核中'), ('publish', '已发布'), ('nopass', '建议修改')) title = models.CharField(max_length=100, blank=True) content = RichTextUploadingField(verbose_name='攻略', default=None, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) img = StdImageField( upload_to=UploadToUUID( path=datetime.now().strftime("strategy/%Y%m%d")), variations={'thumbnail': { 'width': 160, 'height': 100 }}, null=True, blank=True, verbose_name="题图") create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') s_state = models.CharField(max_length=32, choices=state, default='审核中', verbose_name="攻略状态", blank=True) users_like_count = models.IntegerField(blank=True, verbose_name="点赞数", default=0) users_like = models.ManyToManyField(User, related_name="strategy_like", blank=True) collections_count = models.IntegerField(blank=True, verbose_name="收藏数", default=0) collections = models.ManyToManyField(User, related_name="strategy_collections", blank=True) comment_count = models.IntegerField(blank=True, verbose_name="点赞数", default=0) tags = models.ManyToManyField(Tags, related_name='strategy_pick', blank=True) def strategy_img(self): if self.img: return str( '<img src="%s" width="60" height="60" style="object-fit: cover" />' % self.img.url) else: return ' ' strategy_img.short_description = '头像' strategy_img.allow_tags = True class Meta: ordering = ("title", ) verbose_name = '攻略文章' verbose_name_plural = '攻略文章' def __str__(self): return self.title
class Book(models.Model): title = models.CharField(max_length=500) author = models.ForeignKey(Author, null=True, blank=True, related_name='books') category = models.ForeignKey(Category, null=True, blank=True, related_name='books') image = StdImageField(upload_to=UploadToUUID(path='books'), variations={ 'large': (1000, 500, True), 'thumbnail': (200, 200, True), 'medium': (483, 350, True), }) description = models.TextField(blank=True, null=True) price = models.FloatField(default=0.0) is_available = models.BooleanField(default=True) is_for_sale = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) @property def excerpt(self): words = self.description.split() if len(words) > 15: return ' '.join(words[:15]) + '...' return ' '.join(words) def __str__(self): return self.title
class Img_texto(models.Model): texto_modal = models.ForeignKey(Texto_modal, on_delete=models.DO_NOTHING) img = StdImageField(null=True, blank=True, upload_to=UploadToUUID(path='servicos/texto-img'), variations={'normal': (1900, 550, True)}) def __str__(self): return self.texto_modal.servico.nome
class Place(TimeStampedModel): name = models.CharField(_('Name'), max_length=255) image = StdImageField(_('Image'), upload_to=UploadToUUID(path='places'), variations=settings.IMAGE_THUMBNAIL_VARIATIONS, blank=True, null=True) address = models.CharField(_('Address'), max_length=255) class Meta: ordering = ('-created', ) def __str__(self): return self.name @property def today_rating(self): now = timezone.now() return self.vote_set.filter(created__date__gte=now).count() @property def voters(self): now = timezone.now() voters = self.vote_set \ .filter(created__date__gte=now) \ .values_list('username', flat=True) return sorted(list(voters)) or ['Nobody'] def voted_by(self, username): now = timezone.now() return self.vote_set.filter(created__date__gte=now, username=username).exists() @classmethod def most_wanted(cls): now = timezone.now() wanted = cls.objects \ .filter(vote__created__date__gte=now) \ .distinct() \ .annotate(models.Count('vote')) \ .filter(vote__count__gt=0) \ .order_by('-vote__count') if wanted.first(): top_score = wanted.first().vote__count most_wanted = wanted \ .filter(vote__count=top_score) \ .values_list('name', flat=True) else: most_wanted = [ 'Nothing', ] return ', '.join(most_wanted)
class Destaque(models.Model): titulo = models.CharField('Título', max_length=50) descricao = models.CharField('Descrição', max_length=50) imagem = StdImageField(null=True, blank=True, upload_to=UploadToUUID(path='destaques/'), variations={'normal': (1900, 550, True)}) def __str__(self): return self.titulo
class Servico(models.Model): nome = models.CharField(max_length=20) exemplos = models.CharField(max_length=100) imagem = StdImageField(null=True, blank=True, upload_to=UploadToUUID(path='servicos/'), variations={'normal': (1900, 550, True)}) descricao = models.TextField() def __str__(self): return self.nome
class ORMExperience(models.Model): title = models.CharField(max_length=30, blank=False) description = models.TextField(blank=True) picture = StdImageField(upload_to=UploadToUUID(path='experiences'), variations={'large': (1280, 1280), 'medium': (640, 640), 'small': (320, 320)}, blank=True) class Meta: verbose_name = 'Experience' verbose_name_plural = 'Experiences' def __str__(self): return self.title
class Postagem(models.Model): titulo = models.CharField('Título', max_length=100) categoria = models.CharField('Categoria', max_length=50) autor = models.ForeignKey(Equipe, on_delete=models.DO_NOTHING) data_publicacao = models.DateTimeField(blank=True, null=True) imagem = StdImageField(null=True, blank=True, upload_to=UploadToUUID(path='postagens/'), variations={'normal': (1900, 550, True)}) texto = models.TextField() def __str__(self): return self.titulo # retorna um atributo do objeto para url, que relaciona com a view blog_post def get_absolute_url(self): return reverse('blog_post', args=[str(self.titulo)])
class ORMScene(models.Model): title = models.CharField(max_length=30, blank=False) description = models.TextField(blank=True) picture = StdImageField(upload_to=UploadToUUID(path='scenes'), variations={'large': (1280, 1280), 'medium': (640, 640), 'small': (320, 320)}, blank=True) latitude = models.DecimalField(max_digits=10, decimal_places=8) longitude = models.DecimalField(max_digits=11, decimal_places=8) experience = models.ForeignKey(ORMExperience, blank=True, null=True) class Meta: verbose_name = 'Scene' verbose_name_plural = 'Scenes' def __str__(self): return self.title
class CourseOrg(BaseModel): name = models.CharField(max_length=50, verbose_name="机构名称") desc = UEditorField(verbose_name="描述", width=600, height=300, imagePath="courses/ueditor/images/", filePath="courses/ueditor/files/", default="") tag = models.CharField(default="全国知名", max_length=10, verbose_name="机构标签") category = models.CharField(default="pxjg", verbose_name="机构类别", max_length=4, choices=(("pxjg", "培训机构"), ("gr", "个人"), ("gx", "高校"))) click_nums = models.IntegerField(default=0, verbose_name="点击数") fav_nums = models.IntegerField(default=0, verbose_name="收藏数") image = StdImageField(max_length=100, upload_to=UploadToUUID(path=datetime.now().strftime('org/%Y/%m')), verbose_name=u"Logo", variations={'thumbnail': {'width': 100, 'height': 75}}) address = models.CharField(max_length=150, verbose_name="机构地址") students = models.IntegerField(default=0, verbose_name="学习人数") course_nums = models.IntegerField(default=0, verbose_name="课程数") is_auth = models.BooleanField(default=False, verbose_name="是否认证") is_gold = models.BooleanField(default=False, verbose_name="是否金牌") city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name="所在城市") def courses(self): courses = self.course_set.filter(is_classics=True)[:3] return courses class Meta: verbose_name = "课程机构" verbose_name_plural = verbose_name def __str__(self): return self.name def show_image(self): if self.image: href = self.image.url # 点击后显示的放大图片 src = self.image.thumbnail.url # 页面显示的缩略图 # 插入html代码 image_html = '<a href="%s" target="_blank" title="传图片"><img alt="" src="%s"/>' % (href, src) return image_html else: return u'上传图片' show_image.short_description = "Logo" show_image.allow_tags = True
class Equipe(models.Model): TIPO_CARGO_CHOICE = (('Docente', 'Docente'), ('Discente', 'Discente')) CARGO_CHOICE = ( ('Coordenador', 'Coordenador'), ('Diretor Presidente', 'Diretor Presidente'), ('Diretor Vice-Presidente', 'Diretor Vice-Presidente'), ('Diretor de Projetos', 'Diretor de Projetos'), ('Gerente de Projetos', 'Gerente de Projetos'), ('Diretor de Negócios', 'Diretor de Negócios'), ('Gerente de Marketing', 'Gerente de Marketing'), ('Diretor de Processos Internos', 'Diretor de Processos Internos'), ('Gerente de Produtos Internos', 'Gerente de Produtos Internos'), ('Membro', 'Membro'), ) POS_CARGO_CHOICE = ( (1, 'Coordenador'), (2, 'Diretor Presidente'), (3, 'Diretor Vice-Presidente'), (4, 'Diretor de Projetos'), (5, 'Gerente de Projetos'), (6, 'Diretor de Negócios'), (7, 'Gerente de Marketing'), (8, 'Diretor de Processos Internos'), (9, 'Gerente de Processos Internos'), (10, 'Membro'), ) nome = models.CharField(max_length=20) tipo_cargo = models.CharField(max_length=20, choices=TIPO_CARGO_CHOICE) cargo = models.CharField(max_length=20, choices=CARGO_CHOICE) pos_cargo = models.IntegerField(choices=POS_CARGO_CHOICE) sobre = models.TextField() imagem = StdImageField(null=True, blank=True, upload_to=UploadToUUID(path='equipe/aluno'), variations={'normal': (1900, 550, True)}) linkedin = models.CharField(max_length=100) github = models.CharField(max_length=100) def __str__(self): return self.nome
class Migration(migrations.Migration): dependencies = [ ('mainapp', '0011_reportphoto_order'), ] operations = [ migrations.AlterField( model_name='reportphoto', name='order', field=models.IntegerField(verbose_name='order'), ), migrations.AlterField( model_name='reportphoto', name='photo', field=StdImageField(help_text='Report photo', upload_to=UploadToUUID(path=b'photos'), verbose_name='photo'), ), migrations.RunPython(rename_photos) ]
class Course(models.Model): """ 教程 """ name = models.CharField(verbose_name='名称', max_length=30) # 配图 image = StdImageField(verbose_name='配图', blank=True, upload_to=UploadToUUID(path='images'), # 上传路径并使用uuid重新命名 MEDIA_ROOT/images/#UUID#.#EXT# variations={'thumbnail': {"width": 200, "height": 200, "crop": True}}) # 缩略图 # 图片已经上传情况下,直接使用img_url img_url = models.URLField(verbose_name='外部图片url', blank=True, null=True) @python_2_unicode_compatible def __str__(self): return self.name class Meta: verbose_name_plural = verbose_name = '教程' def url(self): """ 获取img_url :return: """ if self.image: return self.image.url else: return "" def image_img(self): if self.image: href = self.image.url # 点击后显示的放大图片 src = self.image.thumbnail.url # 页面显示的缩略图 # 插入html代码 image_html = '<a href="%s" target="_blank" title="图片下载地址"><img alt="" src="%s"/>' % (href, src) return image_html else: return '' image_img.short_description = '显示图片' # 显示在页面的内容 image_img.allow_tags = True # True 显示图片 False显示html代码
class ORMExperience(models.Model): title = models.CharField(max_length=80, blank=False) description = models.TextField(blank=True) picture = StdImageField(upload_to=UploadToUUID(path='experiences'), variations={'large': (1280, 1280), 'medium': (640, 640), 'small': (320, 320)}, blank=True) author = models.ForeignKey(ORMPerson, on_delete=models.CASCADE) share_id = models.CharField(unique=True, max_length=8, null=True, blank=True) saves_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) is_deleted = models.BooleanField(default=False) class Meta: verbose_name = 'Experience' verbose_name_plural = 'Experiences' def __str__(self): return self.title
class ORMProfile(models.Model): person = models.OneToOneField(ORMPerson, related_name='profile', on_delete=models.CASCADE) username = models.CharField(max_length=20, unique=True) bio = models.CharField(max_length=140, blank=True) picture = StdImageField(upload_to=UploadToUUID(path='profiles'), variations={ 'medium': (640, 640), 'small': (320, 320), 'tiny': (160, 160) }, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' def __str__(self): return self.username
class Teacher(BaseModel): user = models.OneToOneField(UserProfile, on_delete=models.SET_NULL, null=True, blank=True,verbose_name="用户") org = models.ForeignKey(CourseOrg, on_delete=models.CASCADE, verbose_name="所属机构") name = models.CharField(max_length=50, verbose_name=u"教师名") work_years = models.IntegerField(default=0, verbose_name="工作年限") work_company = models.CharField(max_length=50, verbose_name="工作单位") work_position = models.CharField(max_length=50, verbose_name="身份") points = models.CharField(max_length=50, verbose_name="教学特点") click_nums = models.IntegerField(default=0, verbose_name="点击数") fav_nums = models.IntegerField(default=0, verbose_name="收藏数") age = models.IntegerField(default=18, verbose_name="年龄") image = StdImageField(max_length=100, upload_to=UploadToUUID(path=datetime.now().strftime('teacher/%Y/%m')), verbose_name=u"头像", variations={'thumbnail': {'width': 100, 'height': 75}}) class Meta: verbose_name = "教师" verbose_name_plural = verbose_name def __str__(self): return self.name def course_nums(self): return self.course_set.all().count() def show_image(self): if self.image: href = self.image.url # 点击后显示的放大图片 src = self.image.thumbnail.url # 页面显示的缩略图 # 插入html代码 image_html = '<a href="%s" target="_blank" title="传图片"><img alt="" src="%s"/>' % (href, src) return image_html else: return u'上传图片' show_image.short_description = "头像" show_image.allow_tags = True
class User(models.Model): """普通用户表""" gender = ( ('male', '男'), ('female', '女'), ) username = models.CharField(max_length=128, verbose_name="用户名", unique=True) password = models.CharField(max_length=256, verbose_name="密码") phone = models.CharField(max_length=13, verbose_name="手机号", blank=True) email = models.EmailField(blank=True, verbose_name="邮箱") sex = models.CharField(max_length=32, choices=gender, default='男', verbose_name="性别", blank=True) avatar = StdImageField( upload_to=UploadToUUID(path=datetime.now().strftime("avatar/%Y%m%d")), variations={ 'thumbnail': { 'width': 100, 'height': 75, 'style': 'objects-fit:cover' } }, null=True, blank=True, verbose_name="头像") background = StdImageField( upload_to=UploadToUUID( path=datetime.now().strftime("background/%Y%m%d")), variations={'thumbnail': { 'width': 100, 'height': 75 }}, null=True, blank=True, verbose_name="背景图") sign = models.CharField(max_length=64, null=True, blank=True, verbose_name="一句话介绍", default='该用户还没有个性签名') introduce = models.CharField(max_length=200, null=True, blank=True, verbose_name="个人简介", default='该用户还没有个人简介') c_time = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tags, related_name='user_pick', blank=True) def avatar_img(self): if self.avatar: return str( '<img src="%s" width="60" height="60" style="object-fit: cover" />' % self.avatar.url) else: return ' ' avatar_img.short_description = '头像' avatar_img.allow_tags = True def background_img(self): if self.background: return str( '<img src="%s" width="200" height="48" style="object-fit:cover"/>' % self.background.url) else: return ' ' background_img.short_description = '背景图' background_img.allow_tags = True def __str__(self): return self.username class Meta: ordering = ['c_time'] verbose_name = '旅途用户' verbose_name_plural = '旅途用户'
class Ads(models.Model): title = models.CharField(max_length=80) url = models.URLField() image = StdImageField(upload_to=UploadToUUID(path='ads'), blank=True) published = models.BooleanField(default=True) date = models.DateTimeField(default=timezone.now)
class ReportUpdatePhoto(models.Model): report_update = models.ForeignKey('mainapp.ReportUpdate', related_name='update_photos') order = models.IntegerField(_('order')) photo = StdImageField(upload_to=UploadToUUID(path='photos/updates'), verbose_name=_("photo"), variations={'large': (800, 600), 'thumbnail': (133, 100)}, help_text=_('Report update photo'))
class UUIDModel(models.Model): image = StdImageField(upload_to=UploadToUUID(path='img'))
class Post(models.Model): class Meta: ''' News 类的内部定义一个 Meta 类,并指定排序属性: ordering 属性用来指定文章排序方式,['-created_time'] 指定了依据哪个属性的值进行排序,这里指定为按照文章发布时间排序, 且负号表示逆序排列。列表中可以用多个项,比如 ordering = ['-created_time', 'title'] , 那么首先依据 created_time 排序,如果 created_time 相同,则再依据 title 排序。 ''' ordering = ['-create_time'] # 数据库中生成的表名称 默认 app名称 + 下划线 + 类名 # db_table = "table_name" # admin中显示的表名称 verbose_name = '文章' # verbose_name加s verbose_name_plural = '文章' # 文章标题 title = models.CharField(verbose_name='标题', max_length=100) # 根据喜好选择admin编辑器:富文本和Markdown is_md = models.BooleanField(verbose_name='markdown语法', default=False) content = models.TextField(verbose_name='内容') content_html = models.TextField(verbose_name='正文Html代码', blank=True, editable=False) # 创建时间 create_time = models.DateField(verbose_name='创建时间', default=datetime.now) # 最后一次修改时间 modified_time = models.DateField(verbose_name='修改时间') # 配图 image = StdImageField(verbose_name='图片', blank=True,null=True, upload_to=UploadToUUID(path='images'), # 上传路径并使用uuid重新命名 MEDIA_ROOT/images/#UUID#.#EXT# variations={'thumbnail': {"width": 200, "height": 200, "crop": True}}) # 缩略图 # 文章摘要,可以没有文章摘要,但默认情况下 CharField 要求我们必须存入数据,否则就会报错。 # 指定 CharField 的 blank=True 参数值后就可以允许空值了。 excerpt = models.CharField(verbose_name='文摘', max_length=200, blank=False) # https://docs.djangoproject.com/en/1.10/topics/db/models/#relationships # 分类 根据需求 一对多关系:一篇文章对应一个分类,一个分类有多个文章 category = models.ForeignKey(Category, verbose_name='分类') # 标签 根据需求 多对多关系: 一篇文章有多个标签,一个标签有多个文章 tag = models.ManyToManyField(Tag, verbose_name='标签', blank=True, null=True) # 作者 author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='作者') # 教程 course = models.ForeignKey(Course, verbose_name='教程', blank=True, null=True) # 阅读量 PositiveIntegerField 类型只允许其值大于等于0 views = models.PositiveIntegerField(verbose_name='阅读量', default=0) # 图片已经上传情况下,直接使用img_url img_url = models.URLField(verbose_name='外部图片url', blank=True, null=True) def url(self): """ 获取img_url :return: """ if self.image: return self.image.url else: return "" def image_img(self): if self.image: href = self.image.url # 点击后显示的放大图片 src = self.image.thumbnail.url # 页面显示的缩略图 # 插入html代码 image_html = '<a href="%s" target="_blank" title="图片下载地址"><img alt="" src="%s"/>' % (href, src) return image_html else: return '' image_img.short_description = '显示图片' # 显示在页面的内容 image_img.allow_tags = True # True 显示图片 False显示html代码 def save(self, *args, **kwargs): """ 将Markdown转为html :param args: :param kwargs: :return: """ if self.is_md: self.content_html = mistune.markdown(self.content) else: self.content_html = self.content super().save(*args, **kwargs) def increate_views(self): self.views += 1 self.save(update_fields=['views']) @python_2_unicode_compatible def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', kwargs={'pk': self.pk})
class Course(BaseModel): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, verbose_name="讲师") course_org = models.ForeignKey(CourseOrg, null=True, blank=True, on_delete=models.CASCADE, verbose_name="课程机构") name = models.CharField(verbose_name="课程名", max_length=50) desc = models.CharField(verbose_name="课程描述", max_length=300) learn_times = models.IntegerField(default=0, verbose_name="学习时长(分钟数)") degree = models.CharField(verbose_name="难度", choices=(("cj", "初级"), ("zj", "中级"), ("gj", "高级")), max_length=2) students = models.IntegerField(default=0, verbose_name='学习人数') fav_nums = models.IntegerField(default=0, verbose_name='收藏人数') click_nums = models.IntegerField(default=0, verbose_name="点击数") notice = models.CharField(verbose_name="课程公告", max_length=300, default="") category = models.CharField(default=u"后端开发", max_length=20, verbose_name="课程类别") tag = models.CharField(default="", verbose_name="课程标签", max_length=10) youneed_know = models.CharField(default="", max_length=300, verbose_name="课程须知") teacher_tell = models.CharField(default="", max_length=300, verbose_name="老师告诉你") is_classics = models.BooleanField(default=False, verbose_name="是否经典") detail = UEditorField(verbose_name="课程详情", width=600, height=300, imagePath="courses/ueditor/images/", filePath="courses/ueditor/files/", default="") is_banner = models.BooleanField(default=False, verbose_name="是否广告位") image = StdImageField( max_length=100, upload_to=UploadToUUID(path=datetime.now().strftime('courses/%Y/%m')), verbose_name=u"封面图", variations={'thumbnail': { 'width': 100, 'height': 75 }}) class Meta: verbose_name = "课程信息" verbose_name_plural = verbose_name def __str__(self): return self.name def lesson_nums(self): return self.lesson_set.all().count() def show_image(self): if self.image: href = self.image.url # 点击后显示的放大图片 src = self.image.thumbnail.url # 页面显示的缩略图 # 插入html代码 image_html = '<a href="%s" target="_blank" title="传图片"><img alt="" src="%s"/>' % ( href, src) return image_html else: return u'上传图片' show_image.short_description = "封面图" show_image.allow_tags = True def go_to(self): from django.utils.safestring import mark_safe return mark_safe("<a href='/course/{}'>跳转</a>".format(self.id)) go_to.short_description = "跳转"