【问题标题】:How to save a file with a BinaryField using Django Form如何使用 Django 表单保存带有 BinaryField 的文件
【发布时间】:2019-05-17 07:52:34
【问题描述】:

我是 Django 的新手。请帮忙。 我想使用表单将图像保存在 BinaryField 中,但它不起作用。 我想使用 BinaryField 将文件直接保存在数据库中,而不是在媒体文件夹中上传。

模型.py:

class serviceDb(models.Model):
    Dev = 1
    QA = 2
    UAT = 3
    Production = 4
    environment_TYPES = (   (Dev, 'Dev'),   (QA, 'QA'), (UAT, 'UAT'),   (Production, 'Production'), )
    application = models.CharField(db_column='Application', max_length=255, blank=True, null=True)  # Field name made lowercase.
    startdate = models.DateField(null=True)
    expiredate = models.DateField(null=True)
    environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES)
    CSR=models.BinaryField(editable=True)

Form.py:

class serviceForm(forms.ModelForm):
    app_attributes = {'oninvalid': 'this.setCustomValidity("Application field is required")', 'oninput': 'this.setCustomValidity("")'}
    startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100)))
    expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100)))
    application = forms.CharField(widget=forms.TextInput(attrs=app_attributes))
    CSR = forms.FileField(required=False)
    class Meta:
        model = serviceDb
        fields = ('application', 'startdate', 'expiredate', 'environment_type','CSR' )

        error_messages = {
            'application': {
                'required': ("Application field is required"),
            },
            }

【问题讨论】:

  • 按照documentationAlthough you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling.
  • 我猜您需要先将文件转换为二进制文件,然后再将其发送到表单,可能在views.py中
  • @ruddra 这不是我想要的。我必须这样做,所以请帮忙

标签: python django django-models django-forms


【解决方案1】:

BinaryField 需要 BinaryData,因此正如@Vaibhav Vishal 建议的那样,您可能需要自行转换它。

到目前为止,我从未使用过 BinaryField,您真的应该考虑不在数据库中保存二进制数据。

但在你的情况下,我建议尝试类似的方法

class ServiceCreateFormView(CreateView):
    template = ...
    form_class = serviceForm  # Should be `ServiceForm` btw.

    def form_valid(self, form):
        uploaded_file = form.files['CSR'].file  # I assume a `InMemoryUploadedFile` instance
        data = uploaded_file.file.read()

        # construct you own instance here using `data`
        self.object = ...

        return HttpResponseRedirect(self.get_success_url())

请提供有关您的问题的更多信息。就像回溯一样,究竟是什么不起作用,您尝试解决什么问题?

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2018-03-23
    • 2011-01-03
    相关资源
    最近更新 更多