【问题标题】:ContentFile not saved in Django model FileFieldContentFile 未保存在 Django 模型 FileField 中
【发布时间】:2017-06-26 09:26:52
【问题描述】:

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

型号:

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:\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.

【问题讨论】:

    标签: python django django-models django-views


    【解决方案1】:

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

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

    the docs

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

    【讨论】:

      【解决方案2】:

      问题其实是你创建了一个没有名字的文件:ContentFile(<content>, name=None)

      在这种情况下,数据库将存储一个空字符串值(''),并且不会在您的磁盘上存储任何文件。 FieldFile 的工作原理是:没有名字?没有文件。

      所以在创建文件的时候需要给一个名字:ContentFile(<content>, name=<file name>)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-12
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多