如何更改 Django 中对象的 FileField?
我有一个名为 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'] 的类型是否正确?谢谢。
I have a model called ClassFile that takes a FileField (document):
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')
Trying to save the below ClassFile instance after a file upload form was submitted fails because request.FILES['file'] does not exist apparently:
f = ClassFile(
document = request.FILES['file'],
description = form.cleaned_data['description'],
shown = form.cleaned_data['shown'],
course = course,
uploader = request.user,
)
f.save()
I was wondering if I was saving this object the proper way. Does request.FILES['file'] have the right type? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
文件的关键是字段名称
document
(不是file
),最好使用cleaned_data
:form.cleaned_data[ 'document']
(或request.FILES['document']
)返回一个UploadedFile
对象。The key for your file is the field name
document
(notfile
), and it's better to usecleaned_data
:form.cleaned_data['document']
(orrequest.FILES['document']
) return aUploadedFile
object.