【问题标题】:check that the dates are entered correctly in a form检查日期是否在表格中正确输入
【发布时间】:2020-12-13 06:54:30
【问题描述】:

我有一个创建事件的表单,我想检查日期是否正确:结束日期大于开始日期或日期不早于实际日期等... 我正在互联网上检查 django 是否对 django.contrib.admin 小部件进行了任何检查,但我找不到任何东西。

在form.hmtl中:

<form method="post">
{% csrf_token %}
<table class="form form-table">
{{ form }}
<tr><td colspan="2"><button type="submit" class="btn btn-info right"> Submit </button></td></tr>
</table>
</form>

在forms.py中:

class EventForm(ModelForm):
   class Meta:
     model = Event
     fields = ('classrom', 'title', 'description', 'start_time',
     'end_time', 'calendar')

   def __init__(self, *args, **kwargs):
     super(EventForm, self).__init__(*args, **kwargs)
     self.fields['start_time'].widget = widgets.AdminTimeWidget()
     self.fields['end_time'].widget = widgets.AdminTimeWidget()

在models.py中:

class Event(models.Model):
classrom = models.CharField(max_length=200)
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()

calendar = models.ForeignKey(Calendar, on_delete = models.CASCADE)

【问题讨论】:

    标签: django django-rest-framework django-forms django-widget django-model-field


    【解决方案1】:

    您可以在.clean() method of the Form [Django-doc] 中执行此检查:

    from django.utils.timezone import now
    from django.core.exceptions import ValidationError
    
    class EventForm(ModelForm):
        class Meta:
            model = Event
            fields = ('classrom', 'title', 'description', 'start_time', 'end_time', 'calendar')
            widgets = {
                'start_time': widgets.AdminTimeWidget()
                'end_time': widgets.AdminTimeWidget()
            }
    
        def clean(self):
            cleaned_data = super().clean()
            start = cleaned_data.get('start_time')
            end = cleaned_data.get('end_time')
            if now() > start:
                raise ValidationError('start time should later than now.')
            if start > end:
                raise ValidationError('end time should later start time.')
            return cleaned_data

    【讨论】:

      猜你喜欢
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 2019-07-11
      相关资源
      最近更新 更多