python - Changing field in Django Form, overriding clean()
问题描述
I have a date, passed as 2019-01-01T00:02
. My objective is to replace the T with a whitespace, 2019-01-01 00:02
.
Using Form, i validate that field and some others.'
klientForm = KlientForm(json.loads(request.body.decode()))
bokningForm = BokningForm(json.loads(request.body.decode()))
if klientForm.is_valid() and bokningForm.is_valid():
#Save model, etc.
I'm using DateTimeField
, and it will not accept the date unless I change it like above. I implemented my own clean() method,
def clean(self):
cleaned_data = super(BokningForm, self).clean()
pumpStart = self.data['pumpStart']
pumpStart = pumpStart.replace("T", " ")
cleaned_data['pumpStart'] = datetime.strptime(pumpStart, "%Y-%m-%d %H:%M")
return cleaned_data
This successfully converts it to a datetime object, I checked using print(cleaned_data)
My issue is that the data is returned to late, as (I think) bokningForm.is_valid()
has already failed, resulting in the model not being saved.
I tried using clean_pumpStart(self):
as in Django Forms but the function was not called when bokningForm.is_valid()
failed, resulting in the same issue as above.
Any help appreciated!
解决方案
You don't need to do any of this. Instead, you should redefine the field itself, supplying the input_formats
attribute:
class BokningForm(forms.ModelForm):
pumpStart = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S'])
...
Now Django will convert the value automatically as part of its own validation process.
Note, if what you're doing is validating JSON, you probably want to use Django REST Framework and its serializers, rather than plain Django forms.
推荐阅读
- php - 使用 INNER JOIN 从 3 个相关表中获取数据
- android - 如何指定要在哪些线程上运行实时查询?
- python-3.x - 创建字段以接受鼠标绘图并将其转换为图像
- php - PHP - 创建一个新对象数组
- ios - 如何检查 SQLite 查询(插入、删除或更新)是否成功?
- django - Django save() 方法不保存
- python - Python BS4 - 如何查找特定类中的所有属性
- c# - 如何使用实体框架将 WPF 文本框中的新文本值添加到数据库?
- solr - Solr Cloud 管理 UI 中缺少 Zookeeper 文件夹
- java - 对象无法转换为整数错误