15

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 .

XMen
  • 29,384
  • 41
  • 99
  • 151

4 Answers4

27

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

Rk..
  • 753
  • 1
  • 10
  • 27
Raekkeri
  • 761
  • 6
  • 6
14

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.

Majid
  • 1,673
  • 18
  • 27
j_syk
  • 6,511
  • 2
  • 39
  • 56
4

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

Diogo
  • 1,086
  • 8
  • 15
  • Not sure if it's a Django version or whatever (we are still on 2.2), but this is the only solution I could find to override the input format for a ModelForm DateTimeField. Creating custom cleaners, settings the global DATETIME_INPUT_FORMATS, and a bunch of other methods didn't work, but this one does. – slumtrimpet Oct 16 '20 at 14:01
0

The input_formats is your friend.

If you accept javascript, then you could make the field use something like jQuery calendar (i.e. a read-only text field and clicking on it will call the jquery code and pop up the calendar widget). You can have this calendar widget as a starting point.

Community
  • 1
  • 1
Laur Ivan
  • 4,117
  • 3
  • 38
  • 62