I
I
Ilya Chichak2019-04-08 19:05:46
Django
Ilya Chichak, 2019-04-08 19:05:46

How to implement Datetime widget in Django 2?

I'm using Django 2.2 In the model field:
USE_TZ = True

class Training(UuidBasedModel):
    client = models.ForeignKey('common.User', on_delete=models.CASCADE, verbose_name=_('Client'))
    canceled = models.BooleanField(default=False, verbose_name=_('Canceled'))
    cancel_reason = models.CharField(default='', max_length=255, blank=True, verbose_name=_('Cancel reason'))
    
    training_datetime = models.DateTimeField(default=timezone.localtime, verbose_name=_('Training date and time'))

The form is as follows:
class TrainingForm(forms.ModelForm):
    def clean(self):
        if self.cleaned_data['client'].trainings_list.filter(training_datetime__date=self.cleaned_data['training_datetime'].date()).exists():
            raise forms.ValidationError({'client': self.SECOND_TRAINING_FOR_SINGLE_CLIENT_ERROR})

    class Meta:
        model = models.Training
        fields = '__all__'
        widgets = {
            'training_datetime': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
        }

Problems:
1) the default value is not inserted
2) after submitting the form, a KeyError occurs at the clean stage, there is no training_datetime.
If you remove the {'type': 'datetime-local'} attribute from the field widget, everything starts working.
But you need exactly datetime-local field with native controls, and datetime - deprecated.
among other things, datetime-local is not supported by firefox. So maybe there are some other options how to solve this problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-04-18
@pyHammer

Use some plugin like bootstrap datepicker. And don't use the built in DataTimeInput

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question