Search code examples
djangouploadfilefield

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?


Solution

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