Issue
I have a form that takes in start_time and end_time, both of which are DateTimeFields in my model.py. However, I want to make sure that the start_time is less than the end_time. I have created a function in my forms.py but it does not seem to be taking any effect. How I can enforce this validation?
my forms.py
class EventForm(ModelForm):
class Meta:
model = Event
# datetime-local is a HTML5 input type, format to make date time show on fields
widgets = {
"start_time": DateInput(
attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M"
),
"end_time": DateInput(
attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M"
),
"title": TextInput(attrs={"placeholder": "Title"}),
"description": TextInput(attrs={"placeholder": "Description"}),
"author": forms.HiddenInput(),
}
fields = ["title", "description", "start_time", "end_time", "author"]
def clean_time(self):
start_time = self.cleaned_data.get('start_time')
end_time = self.cleaned_data.get('end_time')
if start_time > end_time:
raise forms.ValidationError("Start time cannot be greater than end time")
return self.cleaned_data
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
# input_formats parses HTML5 datetime-local input to datetime field
self.fields["start_time"].input_formats = ("%Y-%m-%dT%H:%M",)
self.fields["end_time"].input_formats = ("%Y-%m-%dT%H:%M",)
my views.py for creating event:
def event_create(request):
instance = Event()
data = request.POST.copy()
data["author"] = request.user
form = EventForm(data or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse("cal:calendar"))
return render(request, "cal/create_event.html", {"event": form})
Solution
Use Django form clean method
For more details refer this https://docs.djangoproject.com/en/3.2/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
Try this
class EventForm(ModelForm):
class Meta:
model = Event
# datetime-local is a HTML5 input type, format to make date time show on fields
widgets = {
"start_time": DateInput(
attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M"
),
"end_time": DateInput(
attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M"
),
"title": TextInput(attrs={"placeholder": "Title"}),
"description": TextInput(attrs={"placeholder": "Description"}),
"author": forms.HiddenInput(),
}
fields = ["title", "description", "start_time", "end_time", "author"]
def clean(self): # use this updated
start_time = self.cleaned_data.get('start_time')
end_time = self.cleaned_data.get('end_time')
if start_time > end_time:
raise forms.ValidationError("Start time cannot be greater than end time")
return self.cleaned_data
def __init__(self, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
# input_formats parses HTML5 datetime-local input to datetime field
self.fields["start_time"].input_formats = ("%Y-%m-%dT%H:%M",)
self.fields["end_time"].input_formats = ("%Y-%m-%dT%H:%M",)
Answered By - rahul.m
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.