如何在Django中更改对象的FileField?

时间:2011-06-17 23:06:10

标签: python django django-file-upload

我有一个名为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']是否具有正确的类型?谢谢。

1 个答案:

答案 0 :(得分:0)

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

document = form.cleaned_data['document']

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