djangodjango-modelsmakemigrations

You are trying to change the nullable field 'email' on customuser to non-nullable without a default


I have two models (UserAddress and CustomUser) in my models.py, the field user address in CustomUser was a many to many field but I decided to change it to a foreign key field. But when I ran python manage.py make migrations it asked me to choose a choice:

what should I do: You are trying to change the nullable field 'email' on customuser to non-nullable without a default; we can't do that (the database needs something to populate exis ting rows). Please select a fix:

  1. Provide a one-off default now (will be set on all existing rows with a null value for this column)
  2. Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous dat a migration)
  3. Quit, and let me add a default in models.py

Here is my models.py file:

class UserAddress(models.Model):
    city = models.CharField(max_length=100)
    address = models.CharField(max_length=200)
    zip_code = models.CharField(max_length=15, blank=True)

    def __str__(self):
        return str(self.id)


class CustomUser(AbstractUser):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    user_address = models.ForeignKey(UserAddress, on_delete=models.CASCADE)

Solution

  • class CustomUser(AbstractUser):
       email = models.EmailField(unique=True ,null =True)
      # your other fields
    

    Run python manage.py makemigrations and python manage.py migrate command. The error will be removed.