Xabi Linazasoro
Xabi Linazasoro

Reputation: 69

ContentFile not saved in Django model FileField

I have a problem when saving Strings as file in my Django models, as whenever I try to get the data back, it gives me a ValueError ("attribute has no file associated"). Here's the details:

MODEL:

class GeojsonData(models.Model):
dname = models.CharField(max_length=200, unique=True)
gdata = models.FileField(upload_to='data')
def __str__(self):
    return self.dname

CODE THAT SAVES THE DATA:

cf = ContentFile(stringToBeSaved)
gj = GeojsonDatua(dname = namevar, gdata = cf)
gj.save()

CODE THAT TRIES TO READ THE DATA:

def readGeo(data):
    f = GeojsonData.objects.all().get(id=data.id).gdata
    f.open(mode ='rb')
    geo = f.read()
    return geo

TRACEBACK:

File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Python\Python36-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\app\views.py" in mapa
  80.           geostr = app.readGeo.readGeo(d)

File "C:\app\readGeo.py" in readGeo
  6.    f.open(mode ='rb')

File "C:\Python\Python36-32\lib\site-packages\django\db\models\fields\files.py" in open
  80.         self._require_file()

File "C:Python\Python36-32\lib\site-packages\django\db\models\fields\files.py" in _require_file
  46.             raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)

Exception Type: ValueError at /app/map/1
Exception Value: The 'gdata' attribute has no file associated with it.

Upvotes: 5

Views: 4194

Answers (2)

Sultan
Sultan

Reputation: 944

The problem in fact is that you create a file without name: ContentFile(<content>, name=None).

In this case, the database will store an empty string value (''), and no file will be stored on your disk. The FieldFile works according to the principle: No name? No file.

So you need to give a name when creating a file: ContentFile(<content>, name=<file name>)

Upvotes: 4

Daniel Roseman
Daniel Roseman

Reputation: 599450

You need to save the ContentFile as an actual file. Rather than assigning it directly to the field, you should call the field's save method and pass it in:

gj = GeojsonDatua(dname = namevar)
gj.gdata.save('myfilename', cf)

See the docs.

Note also, if you're always creating your gdata field like this you probably don't want a FileField at all; perhaps use a TextField instead.

Upvotes: 5

Related Questions