如何使用Django Form使用BinaryField保存文件

时间:2019-05-17 07:52:34

标签: python django django-models django-forms

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

  

Model.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"),
            },
            }

1 个答案:

答案 0 :(得分:0)

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())

请提供有关您的问题的更多信息。像回溯一样,什么完全不起作用,您尝试如何解决?