Django FileField throws attribute error when storing ContentFile
I create a ContentFile instance from a string passed to it and try to save it to the model like this:
def generate_file_path(instance, filename):
path = f"{instance.name}/{instance.field}_{filename}"
return path
class SampleModel(models.Model):
name = CharField(max_length=50)
field = CharField(max_length=100)
upload = models.FileField(
_("Skan"),
storage=settings.FILE_STORAGE,
upload_to=generate_file_path
)
file = ContentFile('sample content', name='file.txt')
instance = SampleModel(upload=file, name='name', field='field_info')
instance.save()
But when saving it throws
AttributeError: 'str' object has no attribute 'generate_filename'
which is weird, because FileField should handle ContentFile instance. What am I doing wrong?
It seems that ContentFile
is missing the generate_filename
attribute that the upload_to
function defined in SewageCompanyConsts
is expecting..
You can assign the filename
to the ContentFile
instance explicitly before assigning it to the FileField
:
class SampleModel(models.Model):
upload = models.FileField(
_("Skan"),
storage=settings.FILE_STORAGE,
upload_to=SewageCompanyConsts.generate_file_path
)
file = ContentFile('sample content')
file.name = 'file.txt'
instance = SampleModel(upload=file)
instance.save()