Reputation:
I created a form that runs smoothly, but when I added in a DateTimeField, the form won't pass as valid anymore. I get the error that I inputted the wrong date/time; however, I have tried every date input format, and it still hasn't worked. I have a feeling the issue may lie in my form field for DateTimeField, but am unsure what the exact issue is. I would greatly appreciate any help.
class Lesson(models.Model):
user = models.ForeignKey(User, null=True, default=None, related_name='lessons', on_delete=models.CASCADE)
lesson_instrument = models.CharField(max_length=255, choices=instrument_list, blank=True)
lesson_level = models.CharField(max_length=255, choices=level_list, blank=True)
lesson_length = models.CharField(max_length=255, choices=length_list, blank=True)
lesson_datetime = models.DateTimeField(null=True, blank=True)
lesson_weekly = models.BooleanField(default=False, blank=True)
def __str__(self):
return self.lessons
@receiver(post_save, sender=User)
def create_user_lessons(sender, instance, created, **kwargs):
if created:
Lesson.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_lessons(sender, instance, **kwargs):
for lesson in instance.lessons.all():
lesson.save()
forms.py
class LessonForm(forms.ModelForm):
lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'}))
lesson_level = forms.ChoiceField(choices=level_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'}))
lesson_length = forms.ChoiceField(choices=length_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'}))
lesson_datetime = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class': 'form-control', 'type':'datetime-local'}))
lesson_weekly = forms.BooleanField(required=False)
class Meta:
model = Lesson
fields = ('lesson_instrument', 'lesson_level', 'lesson_length', 'lesson_datetime', 'lesson_weekly')
views.py
def new_lesson(request):
if request.method == 'POST':
form = LessonForm(request.POST)
if form.is_valid():
lessons = form.save(commit=False)
lessons.user = request.user
lessons.save()
messages.success(request,'Lesson successfully created')
return redirect('/teacher/schedule')
else:
messages.error(request, 'Information entered was invalid')
else:
form = LessonForm()
form = LessonForm()
lessons = Lesson.objects.filter(user=request.user)
context = {'form' : form, 'lessons': lessons}
return render(request, 'teacher/new_lesson.html', context)
Upvotes: 0
Views: 1364
Reputation: 2084
Check DATETIME_INPUT_FORMATS
in your settings file. If it's not specified, it'll default to the values shown here.
Then, add a format=
argument to your DateTimeInput
widget (see the Django docs) for more info on how to do this) and make sure that it aligns with one of the formats supported by your DATETIME_INPUT_FORMATS
setting.
Upvotes: 1