用户创建新课程时,formset 没有将图片上传到后端?

formset not uploading pictures to the backend when user creates a new course?

创建新课程时,表单集中的所有数据都会发布到后端,但课程封面图片除外 为什么我的表单集没有上传课程封面,同时我已将字段添加到 OwnerCourseMixin 和 OwnerCourseEditMixin 我看到了我创建的表单集中的封面字段,但它不会只将封面图像保存在我的数据库中。

models.py 
class Course(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,\
         related_name='courses_created', on_delete=models.CASCADE)
    subject = models.ForeignKey(Subject,related_name='courses', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    cover = models.ImageField(upload_to="course_pictures", blank=True,null=True)

我的view.py

class OwnerMixin(object):
    def get_queryset(self):
        qs = super(OwnerMixin, self).get_queryset()
        return qs.filter(owner=self.request.user)


class OwnerEditMixin(object):
    def form_valid(self, form):
        form.instance.owner = self.request.user 
        return super(OwnerEditMixin, self).form_valid(form)


class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin):
    model = Course 
    fields = ['subject', 'title', 'slug','overview','cover']
    success_url = reverse_lazy('courses:manage_course_list')
    
    
class OwnerCourseEditMixin(OwnerCourseMixin):
    fields = ['subject', 'title','slug', 'overview','cover']
    success_url = reverse_lazy('courses:manage_course_list')
    template_name = 'manage/module/formset.html'
    
class CourseCreateView(OwnerCourseEditMixin,
                         OwnerEditMixin,
                         CreateView,
                         PermissionRequiredMixin):
    pass

class CourseModuleUpdateView(TemplateResponseMixin, View):
    template_name = 'manage/module/formset.html'
    course = None 
    
    def get_formset(self, data=None,):
        return ModuleFormSet(instance=self.course,data=data)
      def dispatch(self, request, pk):
        self.course = get_object_or_404(Course,id=pk,owner=request.user)
        return super(CourseModuleUpdateView, self).dispatch(request, pk)
    
    def get(self, request, *args, **kwargs):
        formset = self.get_formset()
      
        return self.render_to_response({'course':self.course,
                                        'formset':formset,})

    
    def post(self, request, *args, **kwargs):
        formset = self.get_formset(data=request.POST,)
        
        
        if formset.is_valid():
            formset.save()
            return redirect('courses:manage_course_list')
        
        return self.render_to_response({'course': self.course,
                                        'formset':formset})

你的问题来自于你的表单中省略了 enctype="multipart/form-data",添加它,它现在就可以工作了!

<form method="post" enctype="multipart/form-data">
    ...
    ...
</form>