Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change DateTime input format in django form

I am trying to change the DateTime format in one of my django forms.

The format I would like it to accept is: day month year hour_minute_seconds timezone 11 Aug 2015 12:00:00 GMT -> %d %b %Y %H:%M:%S %Z

I have been doing some tests but I have not been able to get the right way.

I have disabled the L10N in the settings.py file so I can use the %b month format.

This is my forms.py file content

from django import forms
from django.forms import DateTimeField

from web.apps.customer.models import Reported_VPN_User

class Customer_settings_vpn_Form(forms.ModelForm):

    event_date = DateTimeField(widget=forms.widgets.DateTimeInput(format="%d %b %Y %H:%M:%S %Z"))

    class Meta:
        model = Reported_VPN_User
        fields = '__all__'

When I try to input a date in the required format, the form does not allow me to go ahead.

I have been checking the DATETIME_INPUT_FORMAT (https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-DATETIME_FORMAT) and I dont see what I am looking for, but checking the python date documentation (https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) I see that it should be possible.

How can I modify the datetime format so I can make it work as requested?

ps: I am not an expert in django.

like image 996
Borja Avatar asked Aug 11 '15 14:08

Borja


People also ask

How do I change the date format in Django?

To customize the format a DateField in a form uses we can set the input_formats kwarg [Django docs] on the field which is a list of formats that would be used to parse the date input from the user and set the format kwarg [Django docs] on the widget which is the format the initial value for the field is displayed in.

What is the format of datetime in Django?

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' .

What is DateTimeField?

DateTimeField is a date and time field which stores date, represented in Python by a datetime. datetime instance. As the name suggests, this field is used to store an object of datetime created in python. The default form widget for this field is a TextInput .


1 Answers

Don't use format. Use input_formats instead, which accepts a list of formats:

event_date = DateTimeField(input_formats=["%d %b %Y %H:%M:%S %Z"])
like image 77
mcastle Avatar answered Sep 28 '22 16:09

mcastle