[英]How to sync photos automatically with database in Django?
我是Python和Django的新手。
我正在一個需要Django的項目中。 在此項目中,程序會通過相機連續捕獲照片,並將其存儲在路徑C:\\Users\\admin\\Pictures
。
現在,我希望Django APP自動將這些照片與數據庫同步,而不是登錄Django管理站點並手動上傳。 如何在Django中正確執行此操作?
這是models.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
@python_2_unicode_compatible
class Image(models.Model):
title = models.CharField(max_length=250, blank=True)
original = models.ImageField(upload_to=settings.IMAGE_PREFIX, default='/tmp/none.jpg')
def __str__(self):
return self.title
我寫腳本只是想同步這些照片:
import os
import django
django.setup()
from gallery.models import Image
path = r"C:\Users\admin\Pictures"
for filename in os.listdir(path):
filePath = os.path.join(path, filename)
thisFile = open(filePath, 'rb')
new_img = Image(original=thisFile, title=filename)
new_img.save()
但是我收到如下錯誤消息:
我thisFile
我嘗試將thisFile
傳遞給Image()
時肯定有一些遺漏,但是我只是不知道如何解決。
非常感謝 !
FileField
需要Django File
對象。
import os
import django
from django.core.files import File
django.setup()
from gallery.models import Image
path = r"C:\Users\admin\Pictures"
for filename in os.listdir(path):
filePath = os.path.join(path, filename)
thisFile = File(open(filePath, 'rb'))
new_img = Image(original=thisFile, title=filename)
new_img.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.