Monday, April 28, 2014

Re: Subjectively Required Fields

Your clean method needs to return cleaned_data I believe

On 28/04/2014 10:02 pm, "Daniel Watkins" <dwatkins.gcode@googlemail.com> wrote:
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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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.

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CAHqTbjmnsxeVfLKJq%3DhFCwuTLb4YiWTMCaPb0yBdHW7SXKOBRg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment