ContentFile 未保存在 Django 模型 FileField 中 [英] ContentFile not saved in Django model FileField

查看:24
本文介绍了ContentFile 未保存在 Django 模型 FileField 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Django 模型中将字符串另存为文件时遇到问题,因为每当我尝试取回数据时,它都会给我一个 ValueError(属性没有关联的文件").详情如下:

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:

型号:

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

保存数据的代码:

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

尝试读取数据的代码:

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

追溯:

File "C:PythonPython36-32libsite-packagesdjangocorehandlersexception.py" in inner
  41.             response = get_response(request)

File "C:PythonPython36-32libsite-packagesdjangocorehandlersase.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:PythonPython36-32libsite-packagesdjangocorehandlersase.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:PythonPython36-32libsite-packagesdjangocontribauthdecorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

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

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

File "C:PythonPython36-32libsite-packagesdjangodbmodelsfieldsfiles.py" in open
  80.         self._require_file()

File "C:PythonPython36-32libsite-packagesdjangodbmodelsfieldsfiles.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.

推荐答案

您需要将 ContentFile 保存为实际文件.与其直接将其分配给字段,不如调用该字段的 save 方法并将其传入:

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)

参见 文档.

另请注意,如果您总是像这样创建 gdata 字段,您可能根本不需要 FileField;也许改用 TextField.

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.

这篇关于ContentFile 未保存在 Django 模型 FileField 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆