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.
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.