Unit conversions between model field value and form field value

45 views
Skip to first unread message

Tim Bell

unread,
May 7, 2019, 6:24:09 PM5/7/19
to Django users
Hi,

I have a model with an integer field storing a duration in hours, while I want to present that to users in a form in days. (The choice of these different units is imposed by other factors not under my control.)

So, when saving a form, I need to convert a value in days to hours by multiplying by 24. I've done that with a clean_<fieldname>() method on the form, as described at https://docs.djangoproject.com/en/2.2/ref/forms/validation/. That works fine for when saving a new model.

When editing an existing model however, I need to take the value from the model stored in hours, and convert that to days for display in the edit form. I've considered various places where I could do that conversion, for instance in the edit view, or the form __init__() method, or the model field's value_from_object() method, but none of those choices seem like the obvious choice, and I can't find a recommendation for how to do this either.

What would you suggest? And is the recommended approach actually documented somewhere that I've missed?

Thanks,

Tim

Joe Reitman

unread,
May 7, 2019, 9:35:15 PM5/7/19
to Django users
Hi Tim,

There is a 'Best Practices' guide for Django that recommends making models fat, https://django-best-practices.readthedocs.io/en/latest/applications.html#models. With that it would be logical to do both conversions in the model.

Regards,
Joe

Shashank Singh

unread,
May 7, 2019, 10:11:45 PM5/7/19
to django...@googlegroups.com
One way could be make a custom read only field to show it in current value in days and take a custom field and on save_model take its value as days multiply it with 24 and save it in model's field.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bc42a210-77ba-45bb-ab36-5b6f16d03ec0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jani Tiainen

unread,
May 8, 2019, 6:29:26 AM5/8/19
to django...@googlegroups.com
Hi.

You could create custom form field that makes conversions both ways.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
Reply all
Reply to author
Forward
0 new messages