【问题标题】:Django - how do you turn an InMemoryUploadedFile into an ImageField's FieldFile?Django - 如何将 InMemoryUploadedFile 转换为 ImageField 的 FieldFile?
【发布时间】:2010-10-05 02:05:35
【问题描述】:

我一直在尝试help(django.db.models.ImageField)dir(django.db.models.ImageField),寻找如何从上传的图像创建ImageField 对象。

request.FILES 的图像为InMemoryUploadedFile,但我正在尝试保存包含ImageField 的模型,那么如何将InMemoryUploadedFile 转换为ImageField

你是如何找到这种类型的东西的?我怀疑这两个类有继承关系,但我必须做很多dir() -ing 才能确定我是否要查看。

【问题讨论】:

    标签: django image django-models upload


    【解决方案1】:

    您想在 ModelForm 中这样做吗?

    这就是我对文件字段所做的

    class UploadSongForm(forms.ModelForm):
        class Meta:
            model = Mp3File
    
        def save(self):
            content_type = self.cleaned_data['file'].content_type
            filename = gen_md5() + ".mp3"
            self.cleaned_data['file'] = SimpleUploadedFile(filename, self.cleaned_data['file'].read(), content_type)
            return super(UploadSongForm, self).save()
    

    您可以以它为例,在源代码中查看 InMemoryUploadedFile 类在初始化参数中需要什么。

    【讨论】:

    • 谢谢,明天我会仔细研究您的示例。我正在绕过表单过程,因为我试图避免用户两次上传图像,所以不能做 clean_data 的事情。
    【解决方案2】:

    您可以通过使用表单实例来实现带有文件上传字段的表单,这是视图:

    def form_view(request):
        if request.method == 'POST':
            form = FooForm(request.POST, request.FILES)
            if form.is_valid():
                form.save()
                return render_to_response('result.html')
            return render_to_response('form.html', {
                'form': form;
                'error_messages': form.errors;
            }
        form = FooForm()
        return render_to_response('form.html', {
            'form': form;
        }
    

    form.save() 保存上传的文件以及所有其他字段,因为您在其构造函数中包含 request.FILES 参数。在您的模型中,您必须像这样定义 ModelForm 类的 FooForm 子类:

    class FooForm(ModleForm):
        Meta:
            model = Foo
    

    ...其中 Foo 是 Model 的子类,它描述了您要永久存储的数据。

    【讨论】:

      【解决方案3】:

      您需要将InMemoryUploadedFile 保存到ImageField,而不是将其“转换”为ImageField

      image = request.FILES['img']
      foo.imagefield.save(image.name, image)
      

      其中foo 是模型实例,imagefieldImageField

      或者,如果您要从表单中提取图像:

      image = form.cleaned_data.get('img')
      foo.imagefield.save(image.name, image)
      

      【讨论】:

      • 这个答案不正确。您可以根据需要使用文件内容,而无需将其保存在模型实例中。检查文件属性
      • 完美!谢谢。你节省了我的时间。
      • 如果表单没有绑定到模型怎么办?实际上它需要一个文件,而不是 InMemoryUploadedFile,并且表单没有经过验证。
      猜你喜欢
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2018-05-07
      • 2018-11-04
      • 2019-07-28
      • 2019-12-08
      • 2022-10-06
      • 1970-01-01
      相关资源
      最近更新 更多