Django forms.DateTimeField change input type

Viewed 94

I want to change forms.DateTimeField input type to "d/m/y H:M". How can I do that? I tried this but didn't work:

travel_on = forms.DateTimeField(input_formats='%m/%d/%y %H:%M')

Here's my Ticket Model:

User = settings.AUTH_USER_MODEL
class Ticket(models.Model):
    from_station = models.CharField(max_length=30)
    to_station = models.CharField(max_length=30)
    purchased_on = models.DateTimeField(default=timezone.now)
    travel_on = models.DateTimeField()
    customer = models.ForeignKey(User,on_delete=models.CASCADE)

    def __str__(self):
        return f"Customer:{self.customer.username},From:{self.from_station},To:{self.to_station},Travel on:{self.travel_on},Purchased on:{self.purchased_on}"    

My TicketForm:

from .models import Ticket
from django import forms

class TicketForm(forms.ModelForm):
    travel_on = forms.DateTimeField(input_formats='%m/%d/%y %H:%M')

    class Meta:
        model = Ticket
        fields = ('from_station','to_station','travel_on')
1 Answers

As the documentation on input_formats says:

input_formats

A list of formats used to attempt to convert a string to a valid datetime.date object.

You thus should pass this as:

travel_on = forms.DateTimeField(input_formats=['%d/%m/%y %H:%M'])

so you wrap this in a list. If a pattern fails, Django will move to the next pattern until a pattern matches, or all the input formats are exhausted.

Note that %y only takes the last two digits of a year, so you should write this as 17/08/21 15:39

Related