django 實現手動儲存檔案到model的FileField
通過POST請求,上傳了檔案,想要將檔案儲存在模型的FileField中
request.FILES中的值均為UploadedFile類檔案物件
表單上傳的檔案物件儲存在類字典物件request.FILES中,表單格式需為multipart/form-data
FieldFile.save(name,content,save=True)
name:命名檔名
content:必須是django.core.files.File或django.core.files.base.ContentFile二者之一的一個例項
from django.core.files.base import ContentFile #from django.core.files import File photo=request.FILES.get('file','') user=UserProfile.objects.get(id=uid) if photo: file_content = ContentFile(photo.read()) #建立ContentFile物件 #file_content = File(photo.read()) #建立File物件 user.photo.save(photo.name,file_content) #儲存檔案到user的photo域 user.save()
補充知識:python-ContentFile未儲存在Django模型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)
參見the docs.
另請注意,如果您始終像這樣建立gdata欄位,則可能根本就不需要FileField.也許改用TextField.
以上這篇django 實現手動儲存檔案到model的FileField就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。