djangodjango-modelsdjango-modeladmindjango-model-fielddjango-model-utils

How to resolve this "Invalid default value for a django.models field error"?


I am creating a student model which records homework details of a student. It works in a way that student has been given work to do at home with some deadlines of days or hours. When I migrate, I get this error I am getting this error

  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
    return self.cursor.execute(query, args)
  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
    res = self._query(query)
  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
    db.query(q)
  File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\connections.py", line 254, in query
    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1067, "Invalid default value for 'deadline_type'")

for my this model

class WorkHour(models.Model):
    DAYS= 'D'
    HOURS= 'H'
    STATUS = [
        ('D', 'Days'),
        ('H', 'Hours')
    ]
    student= models.ForeignKey(Student, on_delete=models.CASCADE)
    date= models.DateField(verbose_name='Date')
    deadline_type= models.CharField(max_length=256,choices=STATUS,default= DAYS, verbose_name= "Days/Hours")
    deadline_time = models.IntegerField(verbose_name='Deadline',default=1)

either I add default value in deadline_type, It gives me the above error. I have done the same thing in my other models too. I din;t know what I am doing wrong here.


Solution

  • You cannot have DAYS= 'D' as default, because it's not tuple. Change the field to that:

    deadline_type= models.CharField(max_length=16, choices=STATUS, default=STATUS[0], verbose_name="Days/Hours")
    

    In that way you can delete DAYS= 'D' HOURS= 'H' and default value will be always the first tuple from STATUS.