0

I am trying to render basic HTML template that would allow me to input a date-time values into database using datetime-local input type. However every time I try to enter a value it always return the Enter a valid date/time error

models.py

class AirframeOperation(models.Model):
    id = models.AutoField(primary_key=True)
    takeoff = models.DateTimeField()
    landing = models.DateTimeField()
    flight_time = models.DurationField()
    metadata = models.OneToOneField(
        Metadata,
        on_delete=models.CASCADE
    )

    def save(self, *args, **kwargs):

        self.block_time = self.block_on - self.block_off
        self.flight_time = self.landing - self.takeoff
        return super(AirframeOperation, self).save(*args, **kwargs)

forms.py

class InsertAirframeOperation(forms.ModelForm):

    takeoff = forms.DateTimeField(
        input_formats=['%d-%m-%YT%H:%M'],
        widget=forms.DateTimeInput(
            attrs={
                'type': 'datetime-local',
                'class': 'form-control'
            },
            format='%d-%m-%YT%H:%M')
    )

    landing = forms.DateTimeField(
        input_formats=['%d-%m-%YT%H:%M'],
        widget=forms.DateTimeInput(
            attrs={
                'type': 'datetime-local',
                'class': 'form-control'
            },
            format='%d-%m-%YT%H:%M')
    )

    class Meta:
        model = AirframeOperation
        fields = ['takeoff', 'landing']
        widgets = {}

views.py

@login_required(login_url='/accounts/login/')
def dataentry(request):                                   
    if request.method == 'POST':
        form_meta = forms.InsertMetadata(request.POST)
        form_airframe = forms.InsertAirframeOperation(request.POST)
        print(form_airframe.errors)
        metadata = None
        if form_meta.is_valid():
            metadata = form_meta.save(commit=False)
            metadata.save()
            meta_id = metadata.id
            print(meta_id)
            metadata = Metadata.objects.get(id=meta_id)
        if form_airframe.is_valid():
            airframe = form_airframe.save(commit=False)
            airframe.metadata = metadata
            airframe.save()
        return redirect('/')
    else:
        form_meta = forms.InsertMetadata()
        form_airframe = forms.InsertAirframeOperation()
        return render(request, "dashboard/data_entry.html", {'form': form_meta, 'form2': form_airframe})

data_entry.html

{% extends "base.html" %}

{% block content %}
<div id="data_entry_container">
    <h3>Metadata General</h3>
    <form method="post" action="" enctype="multipart/form-data">
        {% csrf_token %}

        <p>{{ form.errors }}</p>
        <p>{{ form.non_field_errors }}</p>
        {{ form.as_p }}

        <h3>Airframe Operation Metadata</h3>
        <p>{{ form2.errors }}</p>
        <p>{{ form2.non_field_errors }}</p>
        {{ form2.as_p }}

         <input type="submit" value="Save">
    </form>

</div>

{% endblock content %}

I've tried looking up on the documentations as well as trying out solutions listed here yet it still isn't validating correctly

CorvusRex
  • 79
  • 9

1 Answers1

0

Instead of declaring the "input_formats" on the field itself, try declaring it on the init.

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields["takeoff"].input_formats = ["%Y-%m-%dT%H:%M"]

I've been scratching my head on this same problem for about an hour now, and nothing seems to work except this.

It should be noted that as stated in the documentation (https://docs.djangoproject.com/en/3.0/ref/forms/fields/), the DateTimeField should accept an optional argument "input_formats". But as to why it's not working, I have no idea.

If someone can explain this issue better than I, please do.

mutedeuphonies
  • 343
  • 1
  • 15