簡體   English   中英

ContentFile 未保存在 Django 模型 FileField 中

[英]ContentFile not saved in Django model FileField

在我的 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.

您需要將 ContentFile 保存為實際文件。 與其直接將其分配給字段,不如調用該字段的save方法並將其傳入:

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

請參閱文檔

另請注意,如果您總是像這樣創建gdata字段,您可能根本不需要 FileField; 也許使用 TextField 代替。

事實上,問題在於您創建了一個沒有名稱的文件: ContentFile(<content>, name=None)

在這種情況下,數據庫將存儲一個空字符串值('') ,並且不會在您的磁盤上存儲任何文件。 FieldFile 的工作原理是:沒有名字? 無文件。

所以在創建文件的時候需要給一個名字: ContentFile(<content>, name=<file name>)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM