如何将文件分配给Django中的FileField?

时间:2013-05-17 17:36:29

标签: django

如何在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")

1 个答案:

答案 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 Filefrom yourapp.models import File

冲突

One example使用FileFields