Custom widget with custom value in Django admin

China☆狼群 提交于 2019-12-11 19:28:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!