views:

128

answers:

2

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?

+1  A: 

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.

TomA
A: 

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