Python Forum

Full Version: Django- Remove leading zeros in values from database
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

This is my first post and I'm relatively new to python and django so bear with me.

I'm displaying data from my MySQL database. I would like to remove the leading zeros in a certain fields(the obp and slg fields), but only when the value to the left of the decimal point is a 0. If the digit(s) to the left of the decimal point is not 0, then I obviously want that displayed.

For instance,

I'm displaying 0.750
I would like it displayed as .750

I'm displaying 1.300
I want it to remain being displayed as 1.300

I suspect this can be done in the models or in the views. How would I do either one? Any help on this would be greatly appreciated! Thank You.

models.py
class BattingRegStd(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    hr = models.IntegerField(db_column='HR', blank=True, null=True)  # Field name made lowercase.
    obp = models.FloatField(db_column='OBP', blank=True, null=True)  # Field name made lowercase.
    slg = models.FloatField(db_column='SLG', blank=True, null=True)  # Field name made lowercase.
views.py
from django.shortcuts import render
from .models import BattingRegStd
from .models import FieldingRegStd


# Create your views here.
def batting_reg_std_2018(request):
    battingregstd2018 = BattingRegStd.objects.filter(year=2018)
    return render(request, 'playerstats/battingReg2018.html', {'battingregstd2018':battingregstd2018})
HTML[battingReg2018.html]

{% extends "base.html" %}
{% block contents %}

<div align="center">
<table class="equalDivide">
<thead>
<tr>
<th>HR</th>
<th>OBP</th>
<th>SLG</th>

</tr>
</thead>
<tbody>
{% for index in battingregstd2018%}
<td>{{ index.hr}}</td>
<td>{{ index.obp|default_if_none:"—"|floatformat:3 }}</td>
<td>{{ index.slg|default_if_none:"—"|floatformat:3 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<br>
{% endblock %}
Probably the easiest way would be with a custom template filter: https://docs.djangoproject.com/en/2.1/ho...late-tags/

It'd probably end up looking something like this:
>>> def no_zero(value):
...   if "." not in value:
...     return value
...   left, right = value.split(".")
...   if "0" == left:
...     return "." + right
...   return value
...
>>> no_zero("12.34")
'12.34'
>>> no_zero("0.34")
'.34'
>>> no_zero("34")
'34'