问题
In model I have integer field. Meaning of value of this field is "number of days since 1.1.1970", so I wanted to display it in admin interface as a date using AdminDateWidget
to allow easier selection of date.
My only idea is to create new widget to translate integer to date:
class ExpireWidget(AdminDateWidget):
def render(self, name, value, attrs=None):
if isinstance(value, (int, long)):
value = datetime.date(1970, 1, 1) + datetime.timedelta(value)
return super(ExpireWidget, self).render(name, value, attrs)
And following code in admin.py
:
class LdapUserAdminForm(forms.ModelForm):
class Meta:
widgets = {
'shadow_expire': ExpireWidget
}
When I'm displaying it in admin date everything is ok, but before I save it I should translate date to integer. I thought that I could achieve it using clean_field_name
function, but some validation is executed before clean_field_name
(is it clean()
?) and I get error that I should type integer value.
How should I translate date to int before validation?
回答1:
Each widget has method for taking data back from POST/GET and translating that data for Form validation.
It's method def value_from_datadict(self, data, files, name)
You can see it used here: Pseudo-form in Django admin that generates a json object on save
来源:https://stackoverflow.com/questions/9656680/custom-widget-with-custom-value-in-django-admin