0

I've created a simple form to test the DateTimeField.

settings.py

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-GB'

TIME_ZONE = 'Europe/Rome'

USE_I18N = True

USE_L10N = True

USE_TZ = True

USE_THOUSAND_SEPARATOR = True

models.py

from django.utils import timezone

class DateTimeTest(models.Model):
    publishing_date = models.DateTimeField(
        default=timezone.now,
        )

forms.py

class CustomDateTime(forms.DateTimeInput):
    input_type = 'datetime-local'

class DateTimeTestForm(forms.ModelForm):
    publishing_date = forms.DateTimeField(
        widget= CustomDateTime(
            format='%d/%m/%Y %H:%M',
        )
    )

    class Meta:
        model = DateTimeTest
        fields = ['publishing_date']

views.py

def create_datetime(request):
    if request.method == 'POST':
        form = DateTimeTestForm(request.POST or None)
        if form.is_valid():
            new_testdatetime.save()
            return redirect('test')
    else:
        form = DateTimeTestForm()
    context = {
        'form': form,
        }
    template = 'blog/forms/test.html'
    return render(request, template, context)

urls.py

path('test/', views.create_datetime, name='test'),

test.html

{% extends 'base.html' %}

{% load static %}

{% block content %}
  <form method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" class="btn btn-info" value="Post">
  </form>
{% endblock %}

When I try to post a date and time I see this message:

Enter a valid date/time

enter image description here

I remember that when I set the format I can insert a date and time based on the format. What I've wrong?

MaxDragonheart
  • 1,117
  • 13
  • 34

1 Answers1

0
  • The error Enter a valid date/time must have probably occurred because of the format you are using.
  • When you bind the form with a model form validation also checks if the input is compatible with the field on the model.
  • try converting the DateTime input to YYYY-MM-DD HH:MM:SS format when validating the form.
  • Your issue might be resolved by doing so.

Do update me if this resolves your issue.

NoobN3rd
  • 1,223
  • 1
  • 9
  • 19