【发布时间】: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"),
},
}
【问题讨论】:
-
按照documentation
Although 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