Django- Remove leading zeros in values from database - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html) +--- Thread: Django- Remove leading zeros in values from database (/thread-16602.html) |
Django- Remove leading zeros in values from database - ntuttle - Mar-06-2019 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]
RE: Django- Remove leading zeros in values from database - nilamo - Mar-07-2019 Probably the easiest way would be with a custom template filter: https://docs.djangoproject.com/en/2.1/howto/custom-template-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' |