2

Let's say I have the following model MyModel (it is just an example; the real version has hundreds of fields):

class MyModel(models.Model):
    date1 = models.DateField()
    date2 = models.DateField()
    date3 = models.DateField()

When I am saving the model, I get the following error:

ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]

Basically, one of the fields received an empty string as opposed to a proper date format. However, I don't know whether date1, date2, or date3 is causing the problem.

Is there some easy way to check which field returned this ValidationError?

Ralf
  • 16,086
  • 4
  • 44
  • 68
Valachio
  • 1,025
  • 2
  • 18
  • 40
  • 1
    Where are you getting this error? Is it a form or do you call `.full_clean()` manually? Normally the `ValidationError` includes a key of the field that caused the problem. – Ralf Nov 07 '18 at 09:20

3 Answers3

0

You can validate your model fields directly by over-riding save() like this, which will also give field names for which validation failed:

class MyModel(models.Model):
  date1 = models.DateField()
  date2 = models.DateField()
  date3 = models.DateField()

  def save(self, *args, **kwargs):
    self.full_clean()
    super(MyModel, self).save(*args, **kwargs)

However you should avoid this, as explained here.

You can also write a serializer which can be used for other complex validations as well if any in your original model. For doing it via serializer you can do like this:

Create your own validator:

class DateFormatValidator(object):

    def __init__(self, field_name=""):
        self.field_name = field_name

    def __call__(self, value):
        try:
            datetime.datetime.strptime(value, '%Y-%m-%d')
        except ValueError:
            raise serializers.ValidationError("Incorrect data format for {} field, should be YYYY-MM-DD"
                                              .format(self.field_name))

and then use this for every field inside your serializer class, for ex:

date1 = serializers.CharField(validators=[DateFormatValidator(field_name='date1')])
bak2trak
  • 1,062
  • 8
  • 11
0

simple solution: log the data if errors occurs when saving.

class MyModel(models.Model):
     ...

     def save(self, *args, **kwargs):
          try:
               super(MyModel, self).save(*args, **kwargs)
          except Exception as e:
               log.error(self.date1, self.date2, self.date3)
               raise e

I also recommend you to use form in django or Serializer class in django-rest-framework to check the data before saving.

ramwin
  • 5,803
  • 3
  • 27
  • 29
0

Since all three fields are of the same type and are all expecting the same date format, and the fact that validation will begin from top to bottom, it is most likely that the error is caused by the first field.

You can fix it by setting the date input format variable in the settings module with your preferred format. eg

DATE_INPUT_FORMATS = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y']

Here is reference to more supported formats Django project

Ahmadore
  • 23
  • 1
  • 6