1)在course的admin中添加显示课程名和模糊查询:姓名显示的就是所添加的课程名
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name']
search_fields = ['name']
2)配置课程的显示,可以为空的数据直接在后面添加:blank=True
price = models.DecimalField(max_digits=7,decimal_places=2,default=0,verbose_name='售价',blank=True)
summary = models.CharField(max_length=1000,default='',verbose_name='课程介绍',blank=True)
status = models.PositiveSmallIntegerField(default=0,verbose_name='状态',blank=True) # 0:收费 1:免费,默认0
createDatetime = models.DateTimeField(default=datetime.datetime.now(),verbose_name='创建时间',blank=True)
userBuyer = models.ManyToManyField(to=User,related_name='userBuyer_set',verbose_name='购买用户',blank=True)
userShoppingcart = models.ManyToManyField(to=User,related_name='userShoppingcart_set',verbose_name='加入购物车的用户',blank=True)
3)配置收费状态,在Course类下添加代码:在status中后面加上choices=STATUS_CHOICES
class Course(models.Model):
STATUS_CHOICES =(
(0,'收费'),
(1,'免费'),
)
4)使购买用户和购物车用户显示页面更加友好,在admin中设置了:
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
filter_horizontal = ['userBuyer','userShoppingcart']
5)在添加课程时显示自己设定好的类别,在models中的Category下定义一个方法:显示的名字就是上面定义的name值
def __str__(self):
return self.name
6)在购买用户和购物车用户显示用户的账号,所以在user的models类方法下添加方法:
def __str__(self):
return self.account
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
filter_horizontal = ['userBuyer','userShoppingcart']
list_display = ['id','courseName','pCategory','price','summary','status','createDatetime']
list_filter = ['status','createDatetime']
search_fields = ['courseName','price']
8)为了不想让上传的文件到根路径下,而是放入到创建的新的文件夹下,在course的models下先引入os模块,在定义方法,括号里是存储路径,然后再Course类下定义的文件和图片加上:upload_to=save_file和upload_to=save_img
def save_file(instance,filename):
return os.path.join('video',filename)
def save_img(instance,filename):
return os.path.join('static','img',filename)
fileName = models.FileField(upload_to=save_file,verbose_name='文件名称')
imgname = models.ImageField(upload_to=save_img,verbose_name='课程图片')
然后再添加课程后,直接会进入到所设置的文件夹下,刷新数据库,在course的表单中会有两个课程。