@
676529483 自己写字段有点麻烦(项目有多个 Form),插件的话没用过不知道:)
我刚刚在研究了一下,决定在原 Form 的基础上重载他的 clean 函数,完美解决,代码如下:
```
# 自定义基础类
class BaseForm(forms.Form):
# 重载 clean 方法
def clean(self):
# 遍历字典
cleaned_data = {}
for key, value in self.cleaned_data.items():
if value == None:
cleaned_data[key] = self.fields[key].initial
else:
cleaned_data[key] = value
return cleaned_data
```
其他 Form 类只需要继承这个类就好了
例如上文的
```
class NewForm(forms.Form):
...
)
改为
class NewForm(BaseForm):
...
)
```