Дает мне, что объект ошибки 'NoneType' не имеет атрибута 'tutor_courses', я пытаюсь получить набор запросов с курсами, где request.user находится в поле преподавателя. Я пытался сделать поле преподавателя пустым, но это не так работа, как это исправить?
models.py
class Course(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=150, null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='courses/course_images',blank=True,null=True)
cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True)
tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE)
students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True)
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE)
certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True)
languages = LanguageField(blank=True)
rank_score = models.FloatField(default=0.0)
price = models.FloatField(default=0.0)
discount_price = models.FloatField(blank=True, null=True)
forms.py
class SectionForm(forms.ModelForm):
def get_tutor_courses(self):
return self.user.tutor_courses
course = forms.ModelChoiceField(queryset=Course.objects.all())
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(SectionForm, self).__init__(*args, **kwargs)
if user is not None:
tutor_courses = user.tutor_courses.all()
self.fields['course'].queryset = tutor_courses
if not tutor_courses:
self.fields['course'].help_text = "You need to <b>create</b> a course to create sections in it"
class Meta:
model = CourseSections
fields = ('title','course')
views.py
def add_section_to_course(request):
section_form = SectionForm(**{'user': request.user})
if request.method == 'POST':
section_form = SectionForm(request.POST,request.FILES)
if section_form.is_valid():
new_section = section_form.save(commit=False)
new_section.creator.add(request.user)
new_section.save()
return redirect(new_section.get_absolute_url())
else:
section_form = SectionForm()
return render(request,'courses/create_section.html',{'section_form':section_form})