Tomas Andrle
Tomas Andrle

Reputation: 13344

Save a file using a model and non-model-based Form in Django

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?

Upvotes: 0

Views: 449

Answers (2)

Vebjorn Ljosa
Vebjorn Ljosa

Reputation: 18008

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()

Upvotes: 1

Tomas Andrle
Tomas Andrle

Reputation: 13344

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.

Upvotes: 1

Related Questions