出现该问题可能是由于在form表单中没有正确使用enctype属性来设置对于文件的编码类型。在form表单中应该添加enctype="multipart/form-data"属性来告诉服务器上传的数据是文件类型的数据,而不是普通的文本数据。
示例代码:
from django import forms from django.forms import inlineformset_factory from .models import Course, Lesson
class CourseForm(forms.ModelForm): title = forms.CharField(max_length=200) description = forms.CharField(max_length=500) # the image field should be a file type field image = forms.FileField()
class Meta:
model = Course
fields = ('title', 'description', 'image',)
class LessonForm(forms.ModelForm): title = forms.CharField(max_length=200) video = forms.FileField(required=False)
class Meta:
model = Lesson
fields = ('title', 'video',)
LessonFormSet = inlineformset_factory(Course, Lesson, form=LessonForm, extra=1, can_delete=True)
from django.shortcuts import render, redirect from django.urls import reverse from .forms import CourseForm, LessonFormSet
def create_course(request): if request.method == 'POST': course_form = CourseForm(request.POST, request.FILES) lesson_formset = LessonFormSet(request.POST, request.FILES) if course_form.is_valid() and lesson_formset.is_valid(): course = course_form.save() # set course for each lesson created lessons = lesson_formset.save(commit=False) for lesson in lessons: lesson.course = course lesson.save() return redirect(reverse('course_detail', args=[course.id])) else: course_form = CourseForm() lesson_formset = LessonFormSet()
return render(request, 'create_course.html', {'course_form': course_form, 'lesson_formset': lesson_formset})
在上面的代码中,我们添加了enctype="multipart/form-data"来确保form表单以正确的方式接收文件数据。如果您的表单中已添加了该属性但仍无
下一篇:表单具有先前填写的数据。