Arthur Luiz
Arthur Luiz

Reputation: 123

Invalid date django form validation

I am learning Django and building a CRUD but I'm getting an error in my form validation.

This is the form that ** I created**

class addSignForm(forms.ModelForm):
active = forms.CharField(max_length=10)

class Meta:
    model = signs
    fields = ("id", "active", "action", "date", "expiration_date", "add_by", "user_sign")
    widgets = {
        'date': forms.DateTimeInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
    }

This is the date that I am receiving from the request **(also tried format: '%y-%m-%dT%H:%M'

'2000-04-16T18:57'

And when I try to:

if (form.is_valid()):

says that it is an invalid form and that I typed an invalid date

<li>Enter a valid date/time.</li></ul>

can someone help me

Upvotes: 0

Views: 915

Answers (3)

Arthur Luiz
Arthur Luiz

Reputation: 123

i ended up managing to solve the problem, however I did not like the solution because it does not seem the most right ... however I will share it here in case people experience the same problem :)

What i did was:

create a copy of my GET so it becomes mutable

getCopy = request.GET.copy()

after that i converted the DATE that was comming from GET

ts = time.strptime(request.GET['date'], "%Y-%m-%dT%H:%M")
getCopy['date'] = time.strftime("%m/%d/%Y", ts)

and when i call my form.is_valid instead of passing request.GET, i pass my mutable copy of GET with my formatted date :)

Upvotes: 0

Blackdoor
Blackdoor

Reputation: 982

Your widget format just show for client, not for Form.So you can try add a method named clean_date(self) to replace 'T' with whitespace then return it. or add your format into DATETIME_INPUT_FORMATS list of settings.py.

Upvotes: 1

michaeldel
michaeldel

Reputation: 2385

"2000-04-16T18:57" is not %d/%m/%Y %H:%M format but %Y-%m-%dT%H:%M format. Check list date formatters here https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

Upvotes: 1

Related Questions