Reputation: 1170
I want to preprocess values submitted to a CreateView
in order to get them validated. For example, a custom int-parser for a string entered in the form.
In my case I want to convert a string entered in a CreateView
form like "1:54.363" to an integer (with an existing function parse_laptime
), which is then saved in my model:
class Lap(models.Model):
laptime = models.IntegerField(default=0)
How can this be accomplished best? I'm new to Django and tried using a custom Form with overwritten clean
method, but the field fails validation beforehand and is not passed to clean()
.
Upvotes: 1
Views: 174
Reputation: 53774
Laptime is a time and if you expect the user to enter it in the format "1:54.363" the right field to use is TimeField
Validates that the given value is either a datetime.time or string formatted in a particular time format
It seems that you are storing them in the database as microseconds. You would then need to check the form.is_valid() method and do the convertion either using the date time function or split and arithmatic. .
Upvotes: 1
Reputation: 667
I think you are on the right track in using the form to validate your data. However, your input is failing the validation test simply because the input data, formatted as a time value, is not the integer that your model requires.
You should use an unbound field in the form (or an unbound form) that accepts the data as entered - maybe as a character field. Then, use the clean method for this unbound field to confirm that the data can be converted (based on format and/or value). The actual conversion should happen in the view logic, perhaps in the form_valid() method.
Upvotes: 1