Change DateTime input format in django form

梦想与她 提交于 2020-01-21 11:07:06

问题


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.


回答1:


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"])


来源:https://stackoverflow.com/questions/31944563/change-datetime-input-format-in-django-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!