如何在Django中将文件分配给FileField?
我试试:
from django.core.files import File
...
...
att_path = os.path.join(detach_dir, filename)
if not os.path.isfile(att_path):
fp = open(att_path, 'wb')
djangofile = File(fp)
fp.write(part.get_payload(decode=True))
user = User.objects.get(id=1)
files = File.objects.create(src=djangofile, user=user)
fp.close()
但我有这个错误:
AttributeError:类型对象'文件'没有属性'对象'
models.py:
class File(models.Model):
user = models.ForeignKey(User)
src = models.FileField(upload_to="src")
答案 0 :(得分:1)
更改
class File(models.Model):
user = models.ForeignKey(User)
src = models.FileField(upload_to="src")
为:
class UserFile(models.Model): # for example
user = models.ForeignKey(User)
src = models.FileField(upload_to="src")
然后像这样创建它:
files = UserFile.objects.create(src=djangofile, user=user)
from django.core.files import File
与from yourapp.models import File
One example使用FileFields
。