I made a django form with two fields start date and end date and made a formset. When I use the formset in template as
{{ myformset.management_form }}
{% for form in myformset %}
<p>For period {{ forloop.counter }}</p>
{{ form.as_table }}
<br/>
{% endfor %}
<input type = "submit" value = "See Results" id = "daterangeresult">
I got the form with these two fields in two different row. And for multiple forms, it seems not good in looking as all fields are in different row. I then changed to make these two fields to display in a single row as follows
{{ myformset.management_form }}
{% for form in myformset %}
<p>For period {{ forloop.counter }}</p>
<table>
<tr>
<td>Start Date {{form.start_date}}</td>
<td> </td>
<td>End Date {{form.end_date}}</td>
</tr>
</table>
<br/>
{% endfor %}
<input type = "submit" value = "See Results" id = "daterangeresult">
Then this formset fails to validate my form fields which I have validated in forms.py
from django import forms
from functools import partial
from datetime import date
DateInput = partial(forms.DateInput, {'class': 'dateinput'})
class DateRangeForm(forms.Form):
start_date = forms.DateField(widget=DateInput())
end_date = forms.DateField(widget=DateInput())
def clean(self):
if (self.cleaned_data.get('start_date') >= self.cleaned_data.get('end_date')):
raise forms.ValidationError( 'Start date must be less than end date')
elif(self.cleaned_data.get('start_date') > date.today() or self.cleaned_data.get('end_date') > date.today()):
raise forms.ValidationError('Date can not be greater than today')
else:
return self.cleaned_data
How to get two things simultaneously the form field validation and customised display of form in template?