Date validation consisting of three integers in Django

0

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

  • Year;
  • Year and month;
  • Year, month and day;
  • My idea is, after the user has informed the data, validate them by calling the function valida_data (created by me):

    erro = form.valida_data()
    

    Function valida_data created in form :

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

    But there is an error, because I am comparing a IntegerField with a int() .

    Can you help me set up the day, month, and year validation function? Do you know another way to perform validation?

        
    asked by anonymous 22.11.2018 / 11:38

    1 answer

    2

    Do you want to check if the date entered is valid or not? Use the datetime module that knows how to do it chorematically:

    # -*- 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 called manually with print(test_valida_data() == None) (should return True or generate a AssertionError exception) or pytest with pytest valida_data.py .

        
    23.11.2018 / 12:32