【问题标题】:Uploading multiple files in a ModelForm在 ModelForm 中上传多个文件
【发布时间】:2014-11-08 07:15:30
【问题描述】:

我在 Django 中有一个简单的模型:

class Test(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    title = models.CharField(max_length=180, unique=True)
    file1 = models.FileField(upload_to=download_loc)
    preview = models.FileField(upload_to=preview_loc)

file1 是一个文件,我在客户端动态生成 file1(jpg 图像)的“预览”。

我正在尝试将它们中的两个上传到同一个表单上,但我找不到一个简单的方法来做到这一点。 我怎么能用 Jquery 做到这一点?

这是我所拥有的表单的类:

class TestForm(ModelForm):
    class Meta:
        model = Test
        fields = ('title', 'file1') # I don't want to put preview here because it should be done without the user intervention (I don't want the user to see a button with choose file for the preview)

非常感谢!

【问题讨论】:

    标签: jquery django file-upload


    【解决方案1】:

    如果您真的想将缩略图生成集成到模型级别,请使用 django-imagekit https://pypi.python.org/pypi/django-imagekit

    例子:

    from django.db import models
    from imagekit.models import ImageSpecField
    from imagekit.processors import ResizeToFill
    
    class Profile(models.Model):
        avatar = models.ImageField(upload_to='avatars')
        avatar_thumbnail = ImageSpecField(source='avatar',
                                          processors=[ResizeToFill(100, 50)],
                                          format='JPEG',
                                          options={'quality': 60})
    
    profile = Profile.objects.all()[0]
    print profile.avatar_thumbnail.url    # > /media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg
    print profile.avatar_thumbnail.width  # > 100
    

    尽管在大多数情况下,您不应该将预览添加到模型中,因为在 Django 中有很多用于动态生成缩略图的包(在模板级别):

    【讨论】:

      猜你喜欢
      • 2013-06-24
      • 1970-01-01
      • 2020-01-14
      • 2018-05-09
      • 2021-05-13
      • 2011-02-22
      • 2018-01-26
      • 2012-01-12
      • 2013-12-05
      相关资源
      最近更新 更多