Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django Enter a valid date. validation error

Tags:

django

My model

 class Member(models.Model):

dob = models.DateField('dob')

form

class MemberForm(ModelForm):
  dob = forms.DateField(required=False, input_formats='%Y-%m-%d')
  class Meta:
    model = Member
    exclude = ('profile',)   

some view code

if request.method == 'POST': # If the form has been submitted...
        signup_form = SignupForm(request.POST) # A form bound to the POST data
        # Create a formset from the submitted data
        member_formset = MemberFormSet(request.POST, request.FILES)
        # import pdb; pdb.set_trace()
        if signup_form.is_valid() and member_formset.is_valid():
          print 'in valid'
          signup = signup_form.save(request.POST)
          for form in member_formset.forms:
            member = form.save(commit=False)
            member.profile = signup
            # import pdb; pdb.set_trace()
            # print member.objects.all()
            member.save()
          return redirect("/main") # Redirect to a 'success' page

when m submitting the form the error message coming is

Enter a valid date.

What should i do to solve this validation .

like image 593
XMen Avatar asked Feb 03 '12 12:02

XMen


3 Answers

input_formats needs to be a list, see

example:

['%Y-%m-%d',      # '2006-10-25'
'%m/%d/%Y',       # '10/25/2006'
'%m/%d/%y']       # '10/25/06'

https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.DateField

like image 123
Raekkeri Avatar answered Oct 27 '22 00:10

Raekkeri


I prefer to set **DATE_INPUT_FORMATS in settings.py and then define the field like:

dob = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS)

This more DRY than setting it on a per form field basis.

If it's a text field input, I almost always put the accepted format(s) in the field's help_text so that the user can know what format(s) is(are) accepted.

like image 29
j_syk Avatar answered Oct 27 '22 01:10

j_syk


You do not need to add a new field once you already have a DateField in your Model.

You just have to set the input_formats for this field:

self.fields[ 'dob' ].input_formats = [ '%Y-%m-%d' ]

References: DateField and Format Localization

like image 22
Diogo Avatar answered Oct 27 '22 01:10

Diogo