我遇到了一个似乎总是希望尽管我最好的愿望需要的领域的问题.我的’word_search’文本字段始终要求输入数据,但我一直在尝试确保选项允许空白.
我的模特就是这个.您可以看到blank = True,Null = True选项
class IAV(models.Model):
z_score = models.DecimalField(max_digits = 4,decimal_places=4)
screens = models.IntegerField(default=0)
flu_proteins = models.IntegerField(default = 0)
Key_word = models.TextField(blank=True,null=True)
sess = models.ForeignKey(Sess_IAV,default=None)
我的观点是这样的
def new_IAV(request):
if request.method == "POST":
form = IAVForm(request.POST,request.FILES)
if form.is_valid():
sess_ = Sess_IAV.objects.create()
form.save(
for_page=sess_,
z_score = form.cleaned_data("z_score"),
screens = form.cleaned_data("screens"),
flu_proteins = form.cleaned_data("flu_proteins"),
Key_word = form.cleaned_data("key_word"),
)
return redirect(sess_)
else:
print(form.errors)
else:
url=reverse('IAV_home')
return HttpResponseRedirect(url)
我的形式是这样的.你可以看到required = False属性.
class IAVForm(forms.models.ModelForm):
z_score = forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0.0',}))
screens = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0',}))
flu_proteins = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0',}))
key_word = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','rows':1,'cols':10,'placeholder':'keword values','required':'False'}))
class Meta:
model=IAV
fields=('z_score','screens','flu_proteins','key_word')
def save(self,for_page,z_score,screens,flu_proteins,key_word):
self.instance.sess = for_page
self.instance.z_score = z_score
self.instance.screens = screens
self.instance.flu_proteins = flu_proteins
self.instance.key_word = key_word
return super().save()
考虑到模型中存在’blank = True,null = True’选项,我不确定如何将此字段留空.
小部件也说它不是必需的.
解决方法:
试试这个:
class IAVForm(forms.ModelForm):
z_score = forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0.0',}))
screens = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0',}))
flu_proteins = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control','value':'0',}))
key_word = forms.CharField(required=False, widget=forms.Textarea(attrs={'class':'form-control','rows':1,'cols':10,'placeholder':'keword values'}))
首先,您可以创建类(forms.ModelForm).此外,您在引号内需要= False并作为属性.删除引号并将其放在窗口小部件的属性之前.
看看是否有效.