cngkaygusuz
cngkaygusuz

Reputation: 1516

Customized rendering of model fields

This problem arises from DecimalField.

Concretely, when DecimalField gets rendered in a template, it shows every digit after point according to specified accuracy, even if its all zeros, e.g. if you are storing merely

1.248

it is rendered as (assuming 8 digit accuracy)

1.24800000

which is somewhat more inconvenient than the former.

A trivial solution is to define a method that does the rendering a la appetite and use it accordingly but it wouldn't be a DRY solution.

My research in this matter has been unfruitful and it seems this should be resolved by patching django source (as I hardly think people prefers the verbose representation), but I'd like hear from community beforehand.

Upvotes: 1

Views: 58

Answers (1)

patsweet
patsweet

Reputation: 1558

There's a built-in template filter for rendering floats: https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#floatformat

If you want all your figures to appear rounded to the nearest thousandth:

{{ your_float|floatformat:3 }}

If the number of digits after the decimal varies, you could try writing a custom template filter that chops off trailing zeros. The docs are pretty good on writing your own template filters/tags: https://docs.djangoproject.com/en/1.6/howto/custom-template-tags/

EDIT: A more DRY solution might be to define a function in the model and use that in the template instead. It could look something like this:

In models.py where decimal_field is your problem field:

def formated_decimal_field(self):
    value = str(self.decimal_field)
    output = value.rstrip('0').rstrip('.') if '.' in value else value
    return output

This way, you'd just use {{ object.formated_decimal_field }} in your template.

Upvotes: 1

Related Questions