Django create a new column in an already existing table - python

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.

Related

Adding db_table to model added a last_login field

Background: I started a project with a custom User model. However, noob that I am, I was unaware of the AbstractBaseUser class. So I just wrote my own. The app has been deployed to prod and working fine. But now I want to switch to using AbstractBaseUser so I can take advantage of some of the built-in Django utilities (like the pre-made password resetting process). I had done this with a different app and it worked fine. But that one wasn't in prod while I made the change. Because this one is, I needed to keep the old user table while I made the changes with a copy of it. So my first step was to add db_table = test_users to my old user model, so as to keep the prod app running with an unchanged table. I ran the migration, and two unexpected things happened (I'm a noob, and that's why they were unexpected):
The old user table was renamed. I thought a new table would be created. No problem, I quickly copied the new table and named the copy with the old table's name so the prod app could still find its users
A column last_login was added. Why??
Here's my model, with the added db_table
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
password = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
client_id = models.IntegerField(blank=True, null=True)
is_admin = models.BooleanField(default=False)
is_super = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
class Meta:
db_table = "test_users"
The big problem with this is that when I change to AbstractBaseUser and run the migration, I get an error. Looking at the migration file I see that this change creates a migration that all it tries to do is to add last_login to the table. So, of course, the error I get is "Duplicate column name 'last_login'"
So, my question is two-fold:
Why was that column added in the first migration?
If I just run migrate --fake and keep going, will it have unintended consequences? I thought this could be a good solution, given that the migration file shows nothing else is being done, and if the field already exists, then no harm done?
Maybe because you've changed the parent class django automatically change all the migrations that connected to your user class

"BLOB/TEXT column used in key specification without a key length" error in Django

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 AbstractEmailUser model column does not exist

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.

Django migration doesn't always work

Ok So I have some migration issue in django 1.8 and I need to work around by manually dropping my DB table every time.
My problem is following - every time after I change my table by adding new fields and running
python manage.py makemigrations
python manage.py migrate
it says no changes to apply. (migrate folder is empty)
(It is not picking up changes I made in model file )
At the end table stays with old structure and it gives me errors when I test.
If I drop table in DB directly and start again it works but it is annoying since I have to recreate a test data every time.
Is it a bug in migration or just me ?
For example this is my table from models file but it happened before with other tables.
#with_author
class BOM(models.Model):
name = models.CharField(max_length=200,null=True, blank=True)
description = models.TextField(null=True, blank=True)
product= models.ForeignKey(Product, on_delete=models.PROTECT)
material = models.OneToOneField(Material, related_name = 'material')
creation_time = models.DateTimeField(auto_now_add=True)
materialuom = models.CharField(max_length=1,
choices=UOM_CHOICES)
quantity = models.DecimalField(max_digits=19, decimal_places=10)
waste = models.DecimalField(null=True, blank=True,max_digits=19, decimal_places=10)
def __unicode__(self):
return u'%s %s' % ( self.id, self.name)
Ok so I got my work around thanks to comment from #ahmed.
Every time when doing python manage.py makemigrations appname it is mandatory to type the appname .Without the appname functionality is not always working.
However I believe there is still problem in django1.8 migrate process.

I cannot solve Django models.DateField ValidationError

I am stuck with an Error with models.DateField()
First, I did this.
models.py
from datetime import date, datetime
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
birthdate = models.DateField()
Then, I got,
$ python manage.py makemigrations
You are trying to add a non-nullable field 'birthdate' to user_profile without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
So, I did,
models.py
from datetime import date, datetime
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
birthdate = models.DateField(default=date.today)
Then,
$ python manage.py migrate
django.core.exceptions.ValidationError: ["'' は無効な日付形式です。YYYY-MM-DD形式にしなければなりません。"]
The error means, like "'' is invalid for formate of date. You should change to YYYY-MM-DD".
How should I change this code?
Thank you.
/// additional ///
If I can, I don't want to INSERT date INTO birthdate field. But it seems I have to. Can I let it blank?
birthdate = models.DateField(null=True, blank=False)
didn't work.
Python 3.5.1
Django 1.9.1
Sounds like your migration files are messed up. When you do a migration, django would create a migration file that records what you did. So in short, you changed your model code many times, but you never changed your migration file, or you are creating duplicate migration files.
The following should be what you want,
birthdate = models.DateField(null=True, blank=True)
But as you noticed, cleaning up all migration files that related to this change and create a new one should solve the problem.
What you have tried should work:
birthdate = models.DateField(null=True, blank=False)
This allows the database to accept null values (which it does during the migration) and blank means that django will not accept empty values from forms.
Make sure to delete migrations that have been made but not applied. Also try deleting all .pyc's in your project.
Try this,
birthdate = models.DateField(null=True, blank=False)

Categories

Resources