Django上传多个文件很多

时间:2016-04-07 15:03:28

标签: django many-to-many

我想知道,这是我的代码好吗?

我想要的:创建具有上传多个文件功能的表单。 有人可以说多对多吗?可以吗?

我想上传很多文件。它怎么样?

from __future__ import unicode_literals
import uuid
from django.db import models

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('file_uploads/%Y/%m', filename)

# Create your models here.
class Order(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    phone = models.CharField(max_length=255, blank=True)
    reference = models.CharField(max_length=255)
    files = models.ManyToManyField(File)
    deadline = models.DateTimeField(auto_now_add=False, auto_now=False)

class File(models.Model):
    name = models.CharField(max_length=255)
    file = models.FileField(upload_to=get_file_path)

更新:当我尝试makemigrations命令时出现错误:

File "/home/dima/web/files_2016_04/fileupl/flpp/models.py", line 11, in <module>
    class Order(models.Model):
  File "/home/dima/web/files_2016_04/fileupl/flpp/models.py", line 16, in Order
    files = models.ManyToManyField(File)
NameError: name 'File' is not defined

但它定义了。怎么了? 更新:我解决了在Order类

之前移动File类的问题

UPD 谢谢,我用引号解决了ForeignKey(&#39; File&#39;)的问题

2 个答案:

答案 0 :(得分:0)

如果您想保留当前结构,则需要将其放在引号中:

files = models.ManyToManyField(&#39; File&#39;)

答案 1 :(得分:0)

您只需声明File类高于Order类

# Create your models here.
class File(models.Model):
    name = models.CharField(max_length=255)
    file = models.FileField(upload_to=get_file_path)

class Order(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    phone = models.CharField(max_length=255, blank=True)
    reference = models.CharField(max_length=255)
    files = models.ManyToManyField(File)
    deadline = models.DateTimeField(auto_now_add=False, auto_now=False)