一个Course下有N个Lesson
功能需求:每个用户只能看到自己所设置的Course。
models.py
from django.db import models
from django.contrib.auth.models import User
class Course(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='course_user')
title = models.CharField(max_length=200)
overview = models.TextField()
class Lesson(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='lesson_user')
course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name='lesson')
title = models.CharField(max_length=200)
video = models.FileField(upload_to=user_directory_path)
description = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
forms.py
from django import forms
from .models import Course,Lesson
class CreateLessonForm(forms.ModelForm):
class Meta:
model = Lesson
fields = ['course','title','video','description','attach']
def __init__(self,user,*args,**kwargs):
super(CreateLessonForm,self).__init__(*args,**kwargs) # 先调用父类初始化方法
self.fields['course'].queryset = Course.objects.filter(user=user) # 注意这里的queryset
重写_init_()初始化方法,让每个用户只能看到自己所设置的课程标题。
如果没有重写,则是按照fields中的声明,会列出所有用户创建的course。
通过user参数传入当前用户,筛选出当前用户的course值。
网友评论