agenda_culturel/src/agenda_culturel/forms.py

68 lines
2.4 KiB
Python

from django.forms import ModelForm, ValidationError, TextInput
from django.views.generic import FormView
from .models import EventSubmissionForm, Event
from django.utils.translation import gettext_lazy as _
class EventSubmissionModelForm(ModelForm):
class Meta:
model = EventSubmissionForm
fields = ["url"]
class EventForm(ModelForm):
class Meta:
model = Event
fields = '__all__'
widgets = {
'start_day': TextInput(attrs={'type': 'date', 'onchange': 'update_datetimes(event);', "onfocus": "this.oldvalue = this.value;"}),
'start_time': TextInput(attrs={'type': 'time', 'onchange': 'update_datetimes(event);', "onfocus": "this.oldvalue = this.value;"}),
'end_day': TextInput(attrs={'type': 'date'}),
'end_time': TextInput(attrs={'type': 'time'}),
}
def __init__(self, instance, *args, **kwargs):
is_authenticated = kwargs.pop('is_authenticated', False)
super().__init__(instance=instance, *args, **kwargs)
if not is_authenticated:
del self.fields['status']
def clean_start_day(self):
start_day = self.cleaned_data.get("start_day")
if start_day is not None and start_day < date.today():
raise ValidationError(_("The start date cannot be earler than today."))
return start_day
def clean_end_day(self):
start_day = self.cleaned_data.get("start_day")
end_day = self.cleaned_data.get("end_day")
if end_day is not None and start_day is not None and end_day < start_day:
raise ValidationError(_("The end date must be after the start date."))
if end_day is not None and end_day < date.today():
raise ValidationError(_("The end date cannot be earler than today."))
return end_day
def clean_end_time(self):
start_day = self.cleaned_data.get("start_day")
end_day = self.cleaned_data.get("end_day")
start_time = self.cleaned_data.get("start_time")
end_time = self.cleaned_data.get("end_time")
# same day
if start_day is not None and (end_day is None or start_day == end_day):
# both start and end time are defined
if start_time is not None and end_time is not None:
if start_time > end_time:
raise ValidationError(_("The end time cannot be earlier than the start time."))
return end_time