Python 如何使用Django表单保存带有二进制字段的文件

Python 如何使用Django表单保存带有二进制字段的文件,python,django,django-models,django-forms,Python,Django,Django Models,Django Forms,我是Django的新手。请帮忙。 我想使用表单将图像保存在二进制字段中,但它不起作用。 我希望使用BinaryField将文件直接保存到数据库中,而不是上传到媒体文件夹中 Model.py: Form.py: BinaryField需要BinaryData,因此@Vaibhav Vishal建议您可能需要自己对其进行转换 我从来没有使用二进制字段,你应该考虑不保存数据库中的二进制数据。< /P> 但对你来说,我建议你试试这样的 class ServiceCreateFormView(Create

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

Model.py:

Form.py:


BinaryField需要BinaryData,因此@Vaibhav Vishal建议您可能需要自己对其进行转换

<>我从来没有使用二进制字段,你应该考虑不保存数据库中的二进制数据。< /P> 但对你来说,我建议你试试这样的

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

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

尽管你可能会考虑把文件存储在数据库中,但在99%的情况下,它是一个糟糕的设计。此字段不能替代正确的静态文件处理。我想您需要先将文件转换为二进制文件,然后再将其发送到表单,可能是在视图中。py@ruddra这不是我想要的。我必须这么做,所以请帮忙
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"),
            },
            }
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())