我创建了一个运行平稳的表单,但是当我添加DateTimeField时,该表单将不再有效。我收到输入错误的日期/时间的错误;但是,我尝试了每种日期输入格式,但仍然没有用。我觉得问题可能出在我的DateTimeField的表单字段中,但不确定确切的问题是什么。我将不胜感激。
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)
答案 0 :(得分:1)
在设置文件中选中DATETIME_INPUT_FORMATS
。如果未指定,则默认为here所示的值。
然后,将format=
参数添加到DateTimeInput
小部件(请参阅Django docs)以获取有关如何执行此操作的更多信息),并确保其与一种格式对齐DATETIME_INPUT_FORMATS
设置支持。