AM PM not working in django html template

Viewed 144

I am getting Enter a valid date/time. error when trying use AM and PM. Without AM PM I am not getting any error. I am using bootstrap datetimepicker in my html template. here is my code:

froms.py

class BlogForm(ModelForm):
    class Meta:  
     model = Blog
     fields = ['title','body','published']
     widgets = {
         'title': forms.TextInput(attrs={'class':'form-control','placeholder': 'Title'}),
         'published': forms.DateTimeInput(format=['%Y-%m-%d %I:%M %p']) 
         
      }

#html

 <form method="POST"  enctype="multipart/form-data">
       {{from}}
 </form>

<script>
    $(function () {
      $("#datetimepicker1").datetimepicker({
        format: 'YYYY-MM-DD hh:mm:ss a', 
      });
    });
  </script>
1 Answers

In your code you try to provide the format by setting the format for the widget i.e. DateTimeInput, but the problem is that this format will only be used for the initial value of the input and it is not used to parse the submitted values. Instead you also want to pass the input_formats kwarg to the form field i.e. DateTimeField [Django docs].

Also your format seems to be missing the seconds that you set in the javascript? You might need to add %S in the format string in that case:

class BlogForm(ModelForm):
    published = forms.DateTimeField(
        input_formats=['%Y-%m-%d %I:%M:%S %p'],
        widget=forms.DateTimeInput(format='%Y-%m-%d %I:%M:%S %p')
    )
    
    class Meta:
        model = Blog
        fields = ['title','body','published']
        widgets = {
            'title': forms.TextInput(attrs={'class':'form-control','placeholder': 'Title'}),
        }
Related