I have a deal model that contains two date field. First one is start_date and the other one is end_date. My aim is when I save a deal I want to update a readonly field which shows the substraction of these two date_field.
I try to write a widget however I can only get one of the fields. Here is my widget:
class DueToWidget(AdminDateWidget):
def render(self,name,value,attrs=None):
from datetime import timedelta
output = []
output.append(super(AdminDateWidget, self).render(name,value,attrs))
if value:
due_to = value + timedelta(days=1)
output.append(u'<p>Diff : %s</p>' % due_to)
return mark_safe(u''.join(output))
I’m adding one day to the selected date, how can I get the other field’s value ? Or is there any other way to do this ?
If you don’t mind having to refresh to see the diff (that is, you only see it after you save the model), then an easier approach is to add a readonly field in the admin, that points to a function, like this:
Since your goal is just to display extra information in the model’s admin this is the place to put the code, not in a field’s widget or the model’s class.
As the readonly_fields documentation specifies, its behavior is nearly identical as the list_display, that is you can point it to attributes on both the model and the model’s admin, and also to callables and methods.