1.自定义UserProfile替代原始的Use
在Model.py定义
class UserProfile(AbstractUser):
nick_name=models.CharField(max_length=50,verbose_name=u"昵称",default=u"")
birthday=models.DateField(verbose_name=u"生日",null=True)
gender=models.CharField(choices=(("male",u"男"),("female",u"女")),default="female",max_length=100)
address=models.CharField(max_length=100,default=u"")
mobile=models.CharField(max_length=11,null=True,blank=True)
image=models.ImageField(upload_to="image/%Y/%m",default=u"image/default.png",max_length=100,blank=True)
class Meta:
verbose_name=u"用户信息"
verbose_name_plural=verbose_name
def __str__(self):
return self.username
在Setting中设置
AUTH_USER_MODEL="users.UserProfile"
2. 进行操作之前需要Login验证
1.创建一个工具类,mixin_utils.py
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class LoginRequiredMixin(object):
@method_decorator(login_required(login_url='/login'))
def dispatch(self,request,*args,**kwargs):
return super(LoginRequiredMixin,self).dispatch(request,*args,**kwargs)
2.目标类继承工具类
class CourseInfoView(LoginRequiredMixin,View):
'''
课程章节信息
'''
def get(self,request,course_id):
course=Course.objects.get(id=int(course_id))
#查询用户是否已经关联了该课程
user_courses=UserCourse.objects.filter(request.user,course=course)
if not user_courses:
user_course=UserCourse(user=request.user,course=course)
user_course.save()
user_cousers=UserCourse.objects.filter(course=course)
user_ids=[user_couser.user.id for user_couser in user_cousers]
##传进去list
all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)
#取出索引课程id
course_ids=[user_couser.course.id for user_couser in user_cousers]
#获取学过该用户的学过其他的所有课程
relate_courses=Course.objects.filter(id__in=course_ids).order_by("-click_nums")
all_resources=CourseResource.objects.filter(course=course)
return render(request, "course-video.html", {
"course": course,
"course_resources":all_resources,
"relate_courses":relate_courses
})