I'm using Django 3.0.5 and I am trying to create a new column in a table.
The table looks like this:
class VacationModel(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
emp_id = models.IntegerField()
email = models.EmailField()
from_date = models.DateField()
to_date = models.DateField()
reason = models.TextField()
time_sent = models.DateTimeField("date sent")
req_approved = models.BooleanField(default=False, null=True)
req_denied = models.BooleanField(default=False, null=True)
# daysoff_given = models.IntegerField()
def __str__(self):
return self.emp_id
The new column would be daysoff_given. I tried adding this column and after running python manage.py makemigrations I got an error saying django.db.utils.OperationalError: no such column
I tried following some other answers and I deleted the migrations made inside the migrations folder, without deleting the __init__.py file. After running makemigrations again the same error occured and then I deleted the whole model and made a new model.
I think my database is broken, but is there an actual way to avoid this, since it has already happened two times.
Whenever I try to add a new column, it always throws that error and I cannot continue. How can I fix this?
I think the problem is that you created migrations but didn't apply them. Make sure you run both of the following commands after adding the column in the Model.
python manage.py makemigrations
python manage.py migrate
It it doesn't work, please edit your question and add the full trackback error to help us know what is the causing the error.
I have this model in my Django project:
class Institution(models.Model):
name = models.CharField(unique=True, max_length=100, blank=True)
description = models.TextField(max_length=500, null=True, blank=True)
def __str__(self):
return self.name
I run my project completely when I use SQLite ,but when I change my database engine to Mysql I got this error:
MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'name' used in key specification without a key length")
What I must to do?
I got this error because I was trying to create an index for a TextField. I didn't notice I had used TextField for my name field, I was supposed to use CharField.
class myModel(models):
name = models.TextField(max_length=80)
class Meta:
indexes = [ models.Index(fields=['name'])]
Here was my solution.
First, I deleted the migration file created when I added an index in my model for the first time and run python manage.py makemigrations
Second, I removed the index from my model.
class myModel(models):
name = models.TextField(max_length=80)
Third, I run python manage.py makemigrations. It showed "no changes detected".
Fourth, I run python manage.py migrate and I did not get the error again.
To successfully create the index, I had to change the TextField field to CharField and add the index again.
class myModel(models):
name = models.CharField(max_length=80)
class Meta:
indexes = [ models.Index(fields=['name'])]
Running makemigrations and migrate went fine and created the index successfully.
The solution is pretty simple, Just follow their steps.
1 - Dell all the files in the migration folder
2 - Then run the command "python manage.py makemigrations"
3 - Then run the command "python manage.py migrate"
OR
Do it by the help of a simple SQL-lite Query
Adding index Example
alter table test add index index_name(col1(255),col2(255));
Adding unique index Example
alter table test add unique index_name(col1(255),col2(255));
django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value 'tutorial_series_id' that does not have a corresponding value in main_tutorialseries.id.
The above error shows up and cant migrate
These are my models:
from django.db import models
from datetime import datetime
#Create your models here.
class TutorialCategory(models.Model):
tutorial_category = models.CharField(max_length=200)
category_summary = models.CharField(max_length=200)
category_slug = models.CharField(max_length=200, default=1)
class Meta:
#Gives the proper plural name for admin
verbose_name_plural = "Categories"
def __str__(self):
return self.tutorial_category
class TutorialSeries(models.Model):
tutorial_series = models.CharField(max_length=200)
tutorial_category = models.ForeignKey(TutorialCategory, default=1,verbose_name="Category", on_delete=models.SET_DEFAULT)
series_summary = models.CharField(max_length=200)
class Meta:
#Otherwise we get "Tutorial Serie*ss* in admin"
verbose_name_plural = "Series"
def __str__(self):
return self.tutorial_series
class Tutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = models.TextField()
tutorial_published = models.DateTimeField("date published", default = datetime.now())
tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT)
tutorial_slug = models.CharField(max_length=200,default=1)
def __str__(self):
return self.tutorial_title
I faced the same problem just I am also working with the same. All you got to do is to
just delete "migrations" folder from the "main()" and also the db.sqlite file too.
The error is probably occurring because we have Tutorial already in db
which is not linked to TutorialSeries so.., to make it linked to the
db, make the changes above and then again perform commands.
What I got was:
python manage.py makemigrations
Output:
No changes detected
Next one
python manage.py migrate
Output:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
Make sure while performing these commands you have linked Tutorial
with TutorialSeries. And guys making things done this way makes you earlier data lost from the database. Be careful about that.
Have a Nice day & happy coding.😁
You can simply delete all the objects in the main_tutorial table from django shell:
goto command prompt
python manage.py shell
from main.models import Tutorial
Tutorial.objects.all().delete()
(main being the app name here)
This will delete all the objects in the Tutorial table and then makemigrations and migrate and it should work just fine.
In your Tutorial model, you are using a default value for the foreign key field ** tutorial_series **. This causes the migration to check if a record in TutorialSeries exists with id=1 but there is no such data present, so the error is occuring.
To avoid the error while migrating, remove the on_delete=models.SET_DEFAULT and default=1 from our fields to make your models as:
class TutorialSeries(models.Model):
tutorial_series = models.CharField(max_length=200)
tutorial_category = models.ForeignKey(TutorialCategory,verbose_name="Category")
series_summary = models.CharField(max_length=200)
class Meta:
#Otherwise we get "Tutorial Serie*ss* in admin"
verbose_name_plural = "Series"
def __str__(self):
return self.tutorial_series
class Tutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = models.TextField()
tutorial_published = models.DateTimeField("date published", default = datetime.now())
tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", blank=True, null=True) #<--changes
tutorial_slug = models.CharField(max_length=200,default=1)
def __str__(self):
return self.tutorial_title
After this, migrate your models. Then add data to TutorialCategory and TutorialSeries with id=1.
Then revert your models to your initial setup (keeping default=1 and on_delete=models.SET_DEFAULT). Then again run makemigrations and migrate your models. After this, your problem might be solved.
Try to delete all the migration files exept __init__.py and also delete db.sqlite3. After that run makemigrations and migrate again
Try using on_delete = models.CASCADE without a default parameter.
I was dealing with the same issue. I deleted everything inside migrations except _init__.py and also the sqlite database. Then ran- py -3.7 manage.py makemigrations, then after that, py -3.7 manage.py migrate. Then it worked!
I had this issue a while ago.
The above answer maybe correct but it didnt work for me because
-im using postgres, i cant just delete the database
-migration files were commited in git.
My situation was, I have 004 migration file but i cant run it because of IntegrityError.
I checked the file, and i saw it was in operation list.
The first item of list is migrations.CreateModel and the second was migrations.AddField
here are my steps:
I commented the second item in list, only the CreateModel is remaining.
then run the migrate
open the django admin page and add it manually the missing id
you can add it also in database editor or update statement.
uncomment the AddField section and rerun the migrate.
from django.db import models
from datetime import datetime
class TutorialCategory(models.Model):
tutorial_category = models.CharField(max_length=200)
category_summary = models.CharField(max_length=200)
category_slug = models.CharField(max_length=200)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.tutorial_category
class TutorialSeries(models.Model):
tutorial_series = models.CharField(max_length=200)
tutorial_category = models.ForeignKey(TutorialCategory, verbose_name="Category", on_delete=models.CASCADE, blank=True, null=True)
series_summary = models.CharField(max_length=200)
class Meta:
verbose_name_plural = "Series"
def __str__(self):
return self.tutorial_series
class Tutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = models.TextField()
tutorial_published = models.DateTimeField('date published', default=datetime.now)
tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", on_delete=models.CASCADE, blank=True, null=True)
tutorial_slug = models.CharField(max_length=200, default=1)
def __str__(self):
return self.tutorial_title
Try this, it's work for me.
But remember, you will need to type this code before you have done "python3 manage.py makemigrations" and "python3 manage.py migrate"
The following answer was been posted on the Django tutorial comments of sentdex by nice folks namely: "Kevin di" and "JOSEPH Blessingh". The recommendation helped me and worked like charm:
There is a file " db.sqlite3 " in your working directory, you can open it with any database management tools that supports SQLite type.
following the steps:
For example, " DB Browser for SQLite ", you can Google and download it.
Opening the " db.sqlite3 " file, navigate to the Tables.
Find the main_tutorial table. (Maybe you used another table name in the previous lessons, use your table name.)
Delete record from the table: main_tutorial.
Try python manage.py migrate again.
The meaning of Delete Record from the table can be explained as:
- Click main_tutorial
- Then you might see a tab with the name Browse Data
- Click it and you will see your records
- Press Ctrl + Left Mouse button on the number on the left hand side column to select all the rows
- Delete them using right click
I created a CustomUser model, inheriting from AbstractEmailUser.
I wanted to add an avatar field, after finishing it and making migrations but I'm getting the following error:
column account_customuser.avatar does not exist
LINE 1: ...user"."name", "account_customuser"."valid_email", "account_c...
models.py looks like this now
class CustomUser(AbstractEmailUser):
nickname = models.CharField('nickname', max_length=100, unique=True)
name = models.CharField(max_length=200, blank=True, null=True, default=None)
valid_email = models.BooleanField('valid email', default=False, blank=True)
avatar = models.ImageField(upload_to='profile/photo', blank=True, null=True, default=None)
What can I do to correctly add the avatar field?
As stated here: Django Programming error column does not exist even after running migrations
Something may have gone wrong in your migration process.
Go to your database and find a table named django_migrations where
all the migrations are listed.
Find the row with the migration in which you added the avatar column to your model and delete it from the database (only the row).
Migrate again: ./manage.py migrate
Another possibility is that you are using Django Toolbar like what happened here: Django Migration Error: Column does not exist, in which case you need to comment the toolbar in your installed apps and rerun migrations.
Did you apply a new migration with these changes?
You can check this using showmigrations or use makemigrations to create a migration and migrate to apply it.
I've completely wiped all my database tables in order to add a new field to a model since wiping SQL tables clean is the fastest way to do so without going the 'south' route when the SQL data only contains dummy data for testing purposes.
So here's my Model:
class Student(models.Model):
uid = models.ForeignKey(User)
title = models.CharField(max_length=250, help_text='The student name.')
resume = models.FileField(upload_to=get_upload_resume_name)
location = models.ForeignKey(Location)
country = models.ForeignKey(Country)
prim_interest = models.CharField(max_length=250, help_text='Maximum 250 characters.')
sec_interest = models.CharField(max_length=250, help_text='Maximum 250 characters.')
cellphone = models.IntegerField(default=0)
email_verified = models.BooleanField(default=False)
thumbnail = models.FileField(upload_to=get_upload_file_name)
def __unicode__(self):
return self.title
and the last field that I've added called 'thumbnail' is not being created by Django when I call syncdb right after deleting all my tables.
My method of completely wiping the tables has always worked no matter what drastic changes are applied to models.py and suddenly this is not the case for this instance. I could show you more code snippets but I have no clue where else in the Django project has a direct effect on generating models.
What could be causing syncdb to be refusing to write this new field 'thumbnail' to the Student table in the DB?
Could be That south is interfering. You habe no migrations waiting. If I remember well syncdb dos not create tables That south is scheduled to create.
Why not make a south migrate after your syncdb?