redefine default filtering behavior in Django templates

泄露秘密 提交于 2020-02-03 12:44:46

问题


I have a project with many DecimalFields that are rendered in more than 300 templates. I would like that these decimal fields are rendered normalized. I don't care about precission or anything:

decimal.Decimal("10.0000").normalize()

I haven't found a way to change default rendering system. I know there is a humanize and a floatformat filter I could use in my templates. But I need a solution that doesn't mean editing all those files, even if a shell script could be written.

Thanks


回答1:


You could create a subclass of DecimalField where you override DecimalField.__str__ or DecimalField.__unicode__ to suit your needs. This method is called whenever the value needs to be rendered in a template or whatnot. You would only need to change your models.

The code for theField class is here. DecimalField is a subclass of this. Documentation about subclassing Field: http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#writing-a-field-subclass

Also, see this tip abount the __unicode__ method: http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#some-general-advice

Edit: I am waaay to tired to make any sense at the moment.



来源:https://stackoverflow.com/questions/4119151/redefine-default-filtering-behavior-in-django-templates

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