Subjectively Required Fields

28 views
Skip to first unread message

Daniel Watkins

unread,
Apr 28, 2014, 7:28:38 AM4/28/14
to django...@googlegroups.com
Hello all,

We're running in to an interesting validation problem.  We have a model which represents a (specific type of) date interval, bounded by a start date and end date. Both fields are optional, but if end date is specified then start date must be specified. We are creating an instance of this using a ModelForm.

We initially tried to do this with the model's clean method:

    def clean(self):
        if self.end_date and not self.start_date:
            raise ValidationError('Start date must be specified if an end date is specified.')

This works fine if start date is not specified. However, the error is also shown if an invalid date is given, along with the "Invalid date" message against the field. This isn't really what we want (as it's not especially user-friendly).

I'm pretty sure that this is because the form strips out the invalid date from the data it puts in to the model before this is validated, though I'm not 100% sure on this.

Is there any way we can achieve what we want with model validation, or will we have to put the logic in to the form?


Cheers,

Dan

Mario Gudelj

unread,
Apr 28, 2014, 3:40:58 PM4/28/14
to django...@googlegroups.com

Your clean method needs to return cleaned_data I believe

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/468dc535-c494-4418-86c7-c857f66d130d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Venkatraman S

unread,
Apr 29, 2014, 3:10:44 AM4/29/14
to django...@googlegroups.com
What do you mean by an invalid date? IF you are referring to the date format, then why not enforce a jquery datepicker and let the user choose from it - which would make sure that specified date is 'clean'.

If not the above, a closer look at clean() method would help you ;)


--

Nathan McCorkle

unread,
May 2, 2014, 1:55:41 PM5/2/14
to django...@googlegroups.com

JQuery doesn't solve validation on the backend though, so you'd still want some logic there in case someone modifies or goes around the jQuery and sends packets with bad data.

Reply all
Reply to author
Forward
0 new messages