Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error : "You are trying to add a non-nullable field"

Tags:

python

django

I defined below model and getting

error : You are trying to add a non-nullable field 'user' to videodata without a default; we can't do that

models.py

class User(Model):
    userID = models.IntegerField()
    userName = models.CharField(max_length=40)
    email = models.EmailField()
    class Meta:
        ordering = ['userName']
        verbose_name = 'User MetaData'
        verbose_name_plural = 'Users MetaData'
    def __unicode__(self):
        return str(self.userName)

class VideoData(Model):
    video = models.CharField(max_length=40)
    time  = models.IntegerField()
    user = models.ForeignKey(User, related_name='User')
    class Meta:
        verbose_name = 'User_Video MetaData'

Where i am doing wrong????

like image 733
Naresh Avatar asked Jul 11 '15 12:07

Naresh


3 Answers

As the error says, your user field on VideoData is not allowing nulls, so you either need to give it a default user or allow nulls. Easiest way is to allow nulls.

user = models.ForeignKey(User, related_name='User', null=True)

or have a default user

user = models.ForeignKey(User, related_name='User', default=<have your default user id here>)
like image 196
wobbily_col Avatar answered Nov 14 '22 08:11

wobbily_col


I have run into the same problem with my OneToOneField. And, what I did was to delete all the migration files (which are under the directory of migrations under your app), and ran:

python manage.py makemigrations

and

python manage.py migrate

I don't know why, but it worked in my case. It won't hurt you to try what I wrote above.

Good luck!

like image 13
btaek Avatar answered Nov 14 '22 07:11

btaek


Here is what I did to fix the same issue

  1. Comment the foreign key reference in videodata and run the makemigrations and migrate
  2. Add the model in admins.py and make a new entry in table
  3. Now uncomment the foreign key reference and provide a default=1 .Run make migrations and migrate
  4. Remove the default=1 in foreign key field.

Hope this helps. This solution will work everytime you face these kinds of error.

like image 2
ALLSYED Avatar answered Nov 14 '22 07:11

ALLSYED