【问题标题】:question on django FileField handling and clean method关于 django FileField 处理和清理方法的问题
【发布时间】:2021-12-27 00:15:45
【问题描述】:

我有一个相当简单的模型:

class Product(models.Model):
    data = models.JSONField()
    number = models.PositiveIntegerField()

我可以通过表格更新:

class ProductForm(forms.Form):
    def __init__(self, *args, **kwargs):
        product = kwargs.pop("product")
        super().__init__(*args, **kwargs)
        self.fields["number"] = forms.IntegerField()
        self.fields[product.data.keys()[0]] = forms.CharField()
        self.fields[product.data.keys()[1]] = forms.FileField()
            ...

     def clean(self):
         cleaned_data = super().clean()
         print(cleaned_data.get("image")) ## prints None
         print(self.files) ## prints: 

一切正常,我将表单放入模板中并设置了enctype="multipart/form-data" 属性,然后我在TemplateView 中收到表单:

class ProductUpdateView(TemplateView):
    template_name = "update_product.html"

    def post(self, request, *args, **kwargs):
        obj = Product.objects.get(pk = kwargs["pk"])
        print(request.FILES) ## prints the correct filename!
        form = ProductForm(request.POST or None, product = obj)
        for key in request.POST.keys():
            ...
        obj.save()
        context = {'product': obj}
        return render(request, self.template_name, context)

为什么self.files打印None,也cleaned_data.get("image")打印<MultiValueDict: {}>,但在视图中,request.FILES正确知道<MultiValueDict: {'image': [<InMemoryUploadedFile: test.png (image/png)>]}>

【问题讨论】:

  • 视图中的表单如何使用?
  • 我扩展了代码。

标签: django django-views django-forms django-templates


【解决方案1】:

在视图中,您需要正确使用表单并构造它:

ProductForm(request.POST<strong>, request.FILES</strong>, product=obj)

【讨论】:

  • 确实,我不知道我必须手动转发FILES 属性。非常犀利,非常感谢!
猜你喜欢
  • 2018-01-05
  • 1970-01-01
  • 2012-07-05
  • 2012-05-24
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多