如何更改 Django 中对象的 FileField?

发布于 2024-11-16 04:10:32 字数 1008 浏览 2 评论 0原文

我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌若浮生 2024-11-23 04:10:32

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

document = form.cleaned_data['document']

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

The key for your file is the field name document (not file), and it's better to use cleaned_data:

document = form.cleaned_data['document']

form.cleaned_data['document'] (or request.FILES['document']) return a UploadedFile object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文