0

I have a model with a FileField and a form that has a FileField as well. The form is not a ModelForm based on the model but it's a regular Form.

How do I save the uploaded file from the form to the model?

Tomas Andrle
  • 13,132
  • 15
  • 75
  • 92

2 Answers2

1

OK, this is what I was looking for:

from django.core.files.base import ContentFile
def save_file(request):
    mymodel = MyModel.objects.get(id=1)
    file_content = ContentFile(request.FILES['video'].read())
    mymodel.video.save(request.FILES['video'].name, file_content)

Found a good explanation here.

Tomas Andrle
  • 13,132
  • 15
  • 75
  • 92
1

If your model is

class Thing(models.Model):
    document = models.FileField(upload_to='documents')

you can simply do

thing = Thing()
thing.document = request.FILES['Filedata']
thing.save()
Vebjorn Ljosa
  • 17,438
  • 13
  • 70
  • 88