【问题标题】:Validate Date and Time with date in database - Django使用数据库中的日期验证日期和时间 - Django
【发布时间】:2019-06-12 18:18:51
【问题描述】:

我想验证我正在更新TimesheetEntry 模型的表单。我想检查timesheet_clock_out_datetimesheet_clock_out_time 是否不小于timesheet_clock_in_datetimesheet_clock_in_time。如果是,则引发错误“请输入正确的日期”。在我的网址中,我发送 primary keyTimesheetEntry

urls.py

path('useradmin/timesheet/clock-out/<int:pk>', views.ClockOutAddView.as_view(), name='admin_timesheet_clock_out'),

Forms.py

class ClockOutForm(forms.ModelForm):
        class Meta:
           model = TimesheetEntry
           fields = [
           'timesheet_clock_out_date',
           'timesheet_clock_out_time',
           ]

模型.py

class TimesheetEntry(models.Model):
       timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users')
       timesheet_clock_in_date = models.DateField()
       timesheet_clock_in_time = models.TimeField()
       timesheet_clock_out_date = models.DateField(blank=True, null=True)
       timesheet_clock_out_time = models.TimeField(blank=True, null=True)

Views.py

class ClockOutAddView(LoginRequiredMixin, generic.View):

       template_name = 'admin/clock/clock_form.html'
       success_url = '/useradmin/timesheet/'

       def get(self, request, pk, *args, **kwargs):
           form =  ClockOutForm(instance=TimesheetEntry.objects.get(id=pk))
           return render(request, self.template_name, {'form': form})

       def post(self, request, pk, *args, **kwargs):
           form = ClockOutForm(request.POST, instance=TimesheetEntry.objects.get(id=pk))

           if form.is_valid():

               form.save()

               return HttpResponseRedirect(self.success_url)

           return render(request, self.template_name, {'form': form})

如何验证日期和时间。

【问题讨论】:

标签: django django-models django-forms django-templates django-views


【解决方案1】:

我想验证我正在更新 TimesheetEntry 模型的表单。我想检查timesheet_clock_out_datetimesheet_clock_out_time是否不小于timesheet_clock_in_datetimesheet_clock_in_time

您可以添加一个clean(..) function [Django-doc],可能这里最好在模型级别执行此操作,以检查此内容。

from datetime import datetime
from django.core.exceptions import ValidationError

class TimesheetEntry(models.Model):
    timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users')
    timesheet_clock_in_date = models.DateField()
    timesheet_clock_in_time = models.TimeField()
    timesheet_clock_out_date = models.DateField(blank=True, null=True)
    timesheet_clock_out_time = models.TimeField(blank=True, null=True)

    def clean(self):
        if self.timesheet_clock_out_date is not None and self.timesheet_clock_out_time is not None:
            dt1 = datetime.combine(self.timesheet_clock_in_date, self.timesheet_clock_in_time)
            dt2 = datetime.combine(self.timesheet_clock_out_date, self.timesheet_clock_out_time)
            if dt1 > dt2:
                raise ValidationError('Please enter proper date.')
        super(TimesheetEntry, self).clean()

话虽如此,上面的模型是相当“奇怪”的。通常最好使用DateTimeField [Django-doc]。例如,这将防止timesheet_clock_out_dateNone,但timesheet_clock_out_time 不是,反之亦然的奇怪情况。

通常在属性前面加上类的名称,因为这提高了duck类型的能力。

可能更好的建模方法是:

from django.core.exceptions import ValidationError

class TimesheetEntry(models.Model):
    users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users')
    clock_in = models.DateTimeField()
    clock_out = models.DateTimeField(blank=True, null=True)

    def clean(self):
        if self.clock_out is not None and self.clock_in > self.clock_out:
            raise ValidationError('Please enter proper date.')
        super(TimesheetEntry, self).clean()

我建议你看看UpdateView [Django-doc] 类,因为这基本上就是你在这里所做的。你可以传递一个form_class,让它在某个表单上操作。

【讨论】:

    猜你喜欢
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2015-07-22
    • 2015-02-17
    • 2023-04-05
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多