How to Solve You are trying to add a non-nullable field to without a default

This problem happens when you add a new model field in a model has already data.


let's say i have this model below:


class test(models.Model):
    p_1 = models.CharField(max_length=300)
    p_2 = models.CharField(max_length=300)
    p_3 = models.CharField(max_length=300)
    def __str__(self):
        return(self.p_1)

I need to add another field to my model,


class test(models.Model):
    p_1 = models.CharField(max_length=300)
    p_2 = models.CharField(max_length=300)
    p_3 = models.CharField(max_length=300)
    p_4 = models.CharField(max_length=300) #new field
    def __str__(self):
        return(self.p_1)


If I migrate my models, I will get this issue.


Output:


You are trying to add a non-nullable field 'p_4' to header_slider without a default; we can't do that (the database needs something to populate existing rows).


So, how to solve this issue.

1. Adding 'null = True' to the new field.

Code:


p_4 = models.CharField(max_length=300, null=True) #new field


Now we can migrate the models, and the issue will be solved.

2. Adding 'default = " " ' to new filed.

Code:


p_6 = models.CharField(max_length=300, default='test') # default value

If these two ways does not working, can try :

3. Deleting and returning the model

Before talking about this way, I'd to warn you that this way will delete your model data.
so you need to delete your model class in models.py then migrate your app models, after migrations return back the model and migrate the model

Delete Model => Makemigrations Models => Migrate Models => Return Back the models => Makemigrations Models => Migrate Models

I hope this article helps you.

English today is not an art to be mastered it's just a tool to use to get a result