Django datetime not validating right

前端 未结 3 1260
天涯浪人
天涯浪人 2021-01-13 14:33

I\'m using the HTML5 datetime-local input type to try and get some datetime data into my database.

The ModelForm class Meta: l

3条回答
  •  醉梦人生
    2021-01-13 14:51

    The misconception:

    To quote the docs:

    Widgets should not be confused with the form fields. Form fields deal with the logic of input validation and are used directly in templates. Widgets deal with rendering of HTML form input elements on the web page and extraction of raw submitted data.

    Widgets have no influence on validation. You gave your widgets a format argument, but that does not mean the form field validation will use it - it only sets the initial format the widget's content is rendered with:

    format: The format in which this field’s initial value will be displayed.


    The solutions

    Two options:

    • provide the form field (forms.DateTimeField) with the datetime format you would like to use by passing a input_formats argument

      class MyIdealDateForm(forms.ModelForm):
          start = forms.DateTimeField(
              input_formats = ['%Y-%m-%dT%H:%M'],
              widget = forms.DateTimeInput(
                  attrs={
                      'type': 'datetime-local',
                      'class': 'form-control'},
                  format='%Y-%m-%dT%H:%M')
          )
      

      This needs to be done for every form field (and probably by extension even their widgets). What you are doing here is effectively overwriting the settings (see the next point).

    • Add your datetime format to the settings as the first item. This will apply globally to all formfields and widgets that use that setting.

提交回复
热议问题