0

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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</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?

1 Answer 1

1

First I would recommend updating the form definitions to include a label and a help_text. I don't know which version you are using but here is a good place to start: https://docs.djangoproject.com/en/1.6/topics/forms/

Then, in the template you can just do {{ form.start_date.label_tag }}, {{ form.start_date }}, and {{ form.start_date.help_text }} whenever you want to place those into the form.

Second, for the validation issue, you might, instead of overriding clean, override clean_fieldname. In your case clean_start_date and clean_end_date. Once you have those set up for can do

def clean_end_date(self):
    start = self.cleaned_data['start_date'] 
    end = self.cleaned_data['end_date'] 

    if start > end:
        ...do stuff...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.