我有一个类似下面的django表单:
class AnnouncementCreationForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['publish_datetime'].widget = forms.DateTimeInput()
self.fields['publish_datetime'].widget.attrs.update({'placeholder': 'YYYY-MM-DD HH:MM:SS'})
self.fields['publish_datetime'].required=False
self.fields['document'].required=False
class Meta:
model = CompanyAnnouncement
exclude = ['company']
模型如下所示:
class CompanyAnnouncement(models.Model):
class Meta:
ordering = ['publish_datetime']
verbose_name = 'Company Announcement'
verbose_name_plural = 'Company Announcements'
company = models.ForeignKey(Company, on_delete=models.CASCADE)
publish_datetime = models.DecimalField(decimal_places=6, max_digits=18, help_text='Leave blank to publish immediately')
title = models.CharField(max_length=100)
document = models.FileField(upload_to='company_announcements', help_text='', null=True, blank=True)
我已覆盖publish_datetime的默认输入小部件,以使用DateTimeInput,尽管该值是一个小数。这是因为我希望用户输入日期时间,然后将其转换为Unix时间,然后再将其保存在数据库中。这是在视图中完成的:
class AccouncementCreateView(LoginRequiredMixin, CreateView):
form_class = AnnouncementCreationForm
template_name = 'create_announcement.html'
redirect_unauthenticated_users = True
success_url = '/users/my_companies'
def form_valid(self, form):
form.instance.company = Company.objects.filter(crn=self.kwargs['company_spec_url'])[0]
print(type(form.instance.publish_datetime)) # Returns 'datetime.datetime'
if form.instance.publish_datetime:
form.instance.publish_datetime = form.instance.publish_datetime.timestamp()
else:
form.instance.publish_datetime = dt.now().timestamp()
form.save()
return super().form_valid(form)
if语句的后半部分(即输入字段为空)可以工作,并且可以成功地将当前的unix时间存储在db中,但前半部分不起作用。该表单抱怨说“请输入一个数字”,表明它从模型定义而不是从输入小部件定义中进行验证。在让转换发生在form.save()
之前的视图中之前,如何使datetimeinput小部件验证为正常日期时间?