0

I have TransactionForm as follows:

class TransactionForm(ModelForm):
   start_date = forms.DateField(widget=SelectDateWidget)
   duration = forms.ChoiceField(choices=duration_choices)
   class Meta:
      model=Transaction
      fields=(
         'start_date',
         'duration',
         ) 

   def clean(self):
      date = self.cleaned_data.get("start_date")

      if date < datetime.date.today():
         raise forms.ValidationError("The date cannot be in the past!")
      return date

It has a method clean which checks if date entered is at least todays or greater. When some date in past is inserted it shows error on remplate as expected. But when a valid date is entered, I get the following error.

'datetime.date' object has no attribute 'get'

Here is my view.py file

def packages(req):
    if req.method == 'POST':
        form = completeForm(req.POST)
        tf = TransactionForm(req.POST)

        if tf.is_valid():
            return HttpResponse("Some page")
        else:
            errorList = tf.errors['__all__']
            args={'form':form, 'errors':errorList, 'tf':tf}
            return render(req,'main/common/packages.html',args)

    else:   
        form =  completeForm()
        tf = TransactionForm()
        args={'form':form, 'counter':1, 'tf':tf}
        return render(req,'main/common/packages.html',args)

If I remove clean method from form it works fine but I need to validate date without using JavaScript validation.

I found this question closest to mine but its solution is not working or me. Could you please what am I doing wrong?

1 Answer 1

1

You don't validate over multiple fields, thus I suggest trying this instead of def clean(self):

def clean_start_date(self):
    st_date = self.cleaned_data.get("start_date")

    if st_date < datetime.date.today():
        raise forms.ValidationError("The date cannot be in the past!")
    return st_date

Edit: If you did try to validate over multiple fields, that would be the case when documentation suggests using custom clean function.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Mxle, Thanks a lot for your quick response. It is working. but could you please explain why it was not working when I was overriding clean method? What exactly has made the difference here?
My idea is that was because you used date word for a variable. Using such words (and, list, dict, etc) may cause all sorts of magical errors.

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.