python - "This field cannot be blank" even if the field is not empty?
问题描述
models.py:
class Test(PolymorphicModel):
title = models.CharField(max_length=300)
forms.py:
class RestaurantForm(forms.ModelForm):
class Meta:
model = Test
fields = [
'title',
]
def clean_title(self, *args, **kwargs):
title = self.cleaned_data.get("title")
if len(title) < 3:
raise forms.ValidationError("Please, enter at least 3 symbols!")
Okay, when try to submit the form with text, like "aa" it shows error "Please, enter at least 3 symbols!" it works fine, but when add more than 3 symbols it returns me This field cannot be blank which comes from Model, because there is no blank=True
, but field is not empty, I'm confused.
解决方案
django 的clean_xxx
方法希望您返回要使用的清理值,在您的情况下它是无。此外,更好的方法是使用self.add_error
而不是引发 ValidationError。
您的代码应如下所示:
def clean_title(self):
title = self.cleaned_data["title"]
if len(title) < 3:
self.add_error("title", "Please, enter at least 3 symbols!")
return title
推荐阅读
- ibm-content-navigator - 单击搜索模板中的搜索按钮,使用 Content Navigator 插件添加搜索条件
- django - django 中的 form.cleaned_data 为空
- python - 在 TF 2.6 中处理大型数据集时,WGAN 输出“NaN”作为损失
- javascript - 如何在 LWC 中的闪电卡上重叠选择列表字段下拉列表?
- ansible - 在 localhost 上运行脚本的 Ansible 任务
- python-3.x - problem django安装和cmd?
- elasticsearch - 嵌套查询在 Elasticsearch 中是如何工作的?
- excel - 将第一个描述添加到 VBA 中的一组唯一值
- javascript - 在两侧滚动运行动画
- r - 如何将数据集的多行汇总为 R 中的一行?基于列值