1

我有一个创建事件的表格,我想检查日期是否正确:结束日期大于开始日期或日期不早于实际日期等...我正在互联网上检查是否有任何与 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()

在模型.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)
4

1 回答 1

1

您可以在[Django-doc]的.clean()方法中Form执行此检查:

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
于 2020-08-24T15:51:04.983 回答