Reputation: 683
Bear with me because similar questions have been asked before. I'm just don't know how to apply it correctly. I have a field in Charfield(aka string) form called debut that represents dates in the form of 2019-06-19.
I would like to it to be in this format instead 06/19/2019 or 6/19/2019. Could someone please help me with this so that I can call it in my template in that format.
#MODELS
class PlayerLkup(models.Model):
playerid = models.CharField(db_column='playerID', primary_key=True, max_length=255)
birthmonth = models.IntegerField(db_column='birthMonth', blank=True, null=True)
birthday = models.IntegerField(db_column='birthDay', blank=True, null=True)
weight = models.IntegerField(blank=True, null=True)
debut = models.CharField(max_length=255, blank=True, null=True) # this is the field I'm working with
#VIEWS
from django.shortcuts import render
from .models import PlayerLkup
def player_info(request, playerid):
playerdata = PlayerLkup.objects.get(playerid=playerid)
battingstats = playerdata.hittingstats_set.all() #Hittingstats table has a foreign key that references PlayerLkup table
return render(request, 'careerstats/playerpage.html', {'playerdata': playerdata, 'battingstats': battingstats})
#TEMPLATE
{{ playerdata.debut }} # Unformatted call of debut
Upvotes: 0
Views: 171
Reputation: 1609
Since debut is Charfield, user can input date in any format. So it is better to validate from the client side. You can easily be done this in html5 or can validate through Js. So that user is forced to insert in only one format.
<form method="POST" action="">
Debut: <input type="text" size="12" id="id_debut" name="debut" required pattern="\d{4}-\d{1,2}-\d{1,2}" placeholder="yy-mm-dd">
<p><input type="submit"></p>
</form>
Upvotes: 0
Reputation: 33335
In your view function, use the string split()
function to separate the debut into separate year, month, and day values, and then reassemble them back into your desired format.
year, month, day = playerdata.debut.split("-")
new_debut = "%s/%s/%s" % (month, day, year)
Then pass this new value into your template render:
return render(request, 'careerstats/playerpage.html', {'playerdata': playerdata, 'battingstats': battingstats}, 'new_debut': new_debut)
And finally, display it in the template:
{{ new_debut }}
Upvotes: 1