1

我有一个名为 ClassFile 的模型,它采用 FileField(文档):

class ClassFile(models.Model):

    timestamp = models.DateTimeField(auto_now_add=True, editable=False)
    document = models.FileField(upload_to="classFiles/%Y/%m/%d/")
    description = models.TextField('File description', max_length=500)
    shown = models.BooleanField('Allow Students to view this', default=True)
    course = models.ForeignKey(Course, related_name='files', editable=False)
    uploader = models.ForeignKey(User, related_name='class_files_uploaded')

提交文件上传表单后尝试保存以下 ClassFile 实例失败,因为 request.FILES['file'] 显然不存在:

f = ClassFile(
                    document = request.FILES['file'],
                    description = form.cleaned_data['description'],
                    shown = form.cleaned_data['shown'],
                    course = course,
                    uploader = request.user,
                )
f.save()

我想知道我是否以正确的方式保存了这个对象。request.FILES['file'] 的类型是否正确?谢谢你。

4

1 回答 1

0

您的文件的关键是字段名称document(不是file),最好使用cleaned_data

document = form.cleaned_data['document']

form.cleaned_data['document'](或request.FILES['document'])返回一个UploadedFile对象。

于 2011-06-17T23:11:20.460 回答