[Answered ]-In Django, how do I move a file from a model to a directory on disk?

2👍

FileField by default use django.core.files.storage.FileSystemStorage, so it contains a string with file name (path to a file), not a file itself. Just use that filename (path) to copy a file to destination you need.

From here https://docs.djangoproject.com/en/dev/topics/files/#using-files-in-models:

When you use a FileField or ImageField, Django provides a set of APIs
you can use to deal with that file.

Consider the following model, using an ImageField to store a photo:

from django.db import models

class Car(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(upload_to='cars')

Any Car instance will have a photo attribute that you can use to get
at the details of the attached photo:

>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://media.example.com/cars/chevy.jpg'
👤ndpu

Leave a comment