Date validation composed of three integers in Django

Asked

Viewed 89 times

0

In my application I am receiving from the user the day, month and year, the three fields are part of a form and are IntegerField. I don’t want to use the DateField, because the user has the options to inform:

  1. Year;
  2. Year and month;
  3. Year, month and day;

My idea is, after the user informs the data, validate them by calling the function valida_data (created by me):

erro = form.valida_data()

Function valida_data maid in the form:

def valida_data(self):
   if self.fields['mes'] == 2 or 4 or 5 or 6:
      pass

But error occurs, because I’m comparing a IntegerField with a int().

Can you help me in creating the validation function day, month and year? Know another way to perform the validation?

  • 1

    That your condition if self.fields['mes'] == 2 or 4 or 5 or 6, does not make sense. The correct, apparently, would be if self.fields['mes'] in (2, 4, 6). By the way, what is the mistake that gives?

1 answer

1


Do you want to check whether the date entered is valid or not? Use the module datetime who knows how to do it properly:

# -*- coding: utf-8 -*-
from __future__ import print_function
from datetime import date

def valida_data(ano, mes=1, dia=1):
    """ Valida uma data qualquer, recebe `dia`, `mes` e `ano` e devolve
    `True` se a data for válida ou `False` em caso contrário. """
    try:
        __ = date(ano, mes, dia)
        return True

    except ValueError:
        return False

This is the test routine, to check the possible values.

def test_valida_data():
    """ Rotina de teste, verifica a função `valida_data()`. """
    # data válida
    assert valida_data(1980, 10, 12) == True
    # data inválida
    assert valida_data(1982, 2 , 31) == False
    # apenas mês e ano
    assert valida_data(1950, 6) == True
    # data inválida apenas com mês e ano
    assert valida_data(1994, 13) == False
    # apenas o ano
    assert valida_data(1973) == True

This routine can be manually called with print(test_valida_data() == None) (shall return True or generate an exception of AssertionError) or by pytest with pytest valida_data.py.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.