I have an FloatField in my models.py that has to store (among other things) minutes, seconds and milliseconds. It's no biggie to store them in the format of ss.ms, but I have to provide a possibility to insert them via ModelForm in the format of mm.ss.ms.
Problem is, form validation disapproves of mm.ss.ms for FloatField and I'm struggling to find a workaround.
我的models.py中有一个FloatField,它必须存储(除其他外)分钟,秒和毫秒。以ss.ms的格式存储它们并不重要,但我必须提供通过ModelForm以mm.ss.ms格式插入它们的可能性。问题是,表单验证不支持FloatField的mm.ss.ms,我很难找到解决方法。
_clean functions are great, but run after the Django validations. How to clean data from form before it gets validated by Django?
_clean函数很棒,但是在Django验证之后运行。如何在Django验证之前清除表单中的数据?
EDIT:
models.py
from django.db import models
class Result(models.Model):
date = models.DateField()
result = models.FloatField()
rank = models.IntegerField(blank=True, null=True)
forms.py
class AddResult(forms.ModelForm):
class Meta:
model = Result
fields = ('result', 'rank', 'date')
def __init__(self, *args, **kwargs):
self.profile = kwargs.pop('profile', None)
super(AddResult, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.label_class = 'form-label-div'
self.helper.field_class = 'form-field-div'
self.helper.label_class = 'col-xs-4'
self.helper.field_class = 'col-xs-8'
self.helper.layout = Layout(
Div(
Div(
'result',
css_class="col-xs-4",
),
Div(
'rank',
css_class="col-xs-4",
),
css_class="row",
),
Div(
Div(
'date',
css_class="col-xs-4",
css_id="date-picker"
),
Div(
css_class="col-xs-4",
css_id="date-picker"
),
css_class="row",
)
)
def save(self, commit=True):
result = super(AddResult, self).save(commit=False)
if self.profile:
result.profile = self.profile
result.save()
PS! Originally I wrote that I had a problematic IntegerField, but that was some kind of a brain fart. We're talking about a FloatField of course. The main question remains the same.
PS!最初我写道我有一个有问题的IntegerField,但那是一种脑屁。我们当然在谈论FloatField。主要问题仍然是一样的。
1 个解决方案
#1
1
I would suggest you not to use models forms instead use a forms.form and in your view before the ** form.is_valid() ** try to retrieve the form fields with the help of REQUEST method. May be this helps.
我建议你不要使用模型表单而是使用forms.form并在** form.is_valid()**之前的视图中尝试在REQUEST方法的帮助下检索表单字段。可能这有帮助。
#1
1
I would suggest you not to use models forms instead use a forms.form and in your view before the ** form.is_valid() ** try to retrieve the form fields with the help of REQUEST method. May be this helps.
我建议你不要使用模型表单而是使用forms.form并在** form.is_valid()**之前的视图中尝试在REQUEST方法的帮助下检索表单字段。可能这有帮助。