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)
Related
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.
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
I've the following Django model:
class Apple(models.Model):
text = models.TextField()
I've already many records, and I'd like to add a subject field to the model, so it'll look like:
class Apple(models.Model):
text = models.TextField()
subject = models.CharField(max_length = 128)
. In this case I run a makemigrations, but since subject can be empty, I need to set a default value either in the model, or in the migration file.
What would be the correct procedure if I'd like to take the subject from the text for the already existing database lines (for instance: text[:64])?
My solution would be to create a migration with a default value, run a management command to update the values, and with a new migration remove the default value for the subject. Is there a better solution? What is it? Can I somehow combine / do this in the migration itself?
Python: 3.4.5
Django: 1.9.2
For some databases including postgresql, it can be quicker to add a nullable field, therefore I would change your approach to:
schema migration creates the field with null=True (no need to set a default)
data migration populates the field
schema migration removes null=True from field
You can combine the three operations in one migration file. However the Django docs for data migrations recommend that you keep them separate.
You can do it in migration itself, create a migration file with blank=True, null=True in subject field.
class Apple(models.Model):
text = models.TextField()
subject = models.CharField(max_length=128, blank=True, null=True)
Then create another empty migration file.
python manage.py makemigrations --empty yourappname
Paste below code in that file.
from django.db import migrations
def set_subject(apps, schema_editor):
Apple = apps.get_model('yourappname', 'Apple')
for a in Apple.objects.all():
a.subject = a.text
a.save()
class Migration(migrations.Migration):
dependencies = [
('yourappname', 'name of above migration file'),
]
operations = [
migrations.RunPython(set_subject),
]
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.
Whenever I add a new column to my model I get:
django.db.utils.OperationalError: no such column: companies_company.[name of added column]
For example, I just added "employee_count" and whenever I run
python manage.py makemigrations
I get:
django.db.utils.OperationalError: no such column: companies_companyadmin.employee_count
My model.py looks like this:
from django.db import models
import csv
class Company(models.Model):
name = models.CharField(max_length=70, blank=True)
description = models.CharField(max_length=1200, blank=True)
employee_count = models.IntegerField(blank=True)
class CompanyAdmin(models.Model):
name = models.CharField(max_length=70, blank=True)
description = models.CharField(max_length=1200, blank=True)
employee_count = models.(blank=True)
with open("organizationTest.txt","rU") as f:
reader = csv.reader(f)
for row in reader:
_, created = Company.objects.get_or_create(
name=row[3].decode('latin-1').encode('utf8'),
description=row[15].decode('latin-1').encode('utf8'),
)
The CSV part is simply to populate my DB (I should probably do it somewhere else).
And my admin.py:
from django.contrib import admin
from .models import Company
class CompanyAdmin(admin.ModelAdmin):
pass
admin.site.register(Company, CompanyAdmin)
This also happens when I try to run the server or "syncdb".
If anyone knows why this is happening and how I could fix this I would love to know! Thanks in advance! I'm happy to answer any questions you may have.
In my case I had an initial value in some Querysets of an updated model. When I removed these initial statements, makemigrations had worked.
Appears my original answer wasn't clear enough.
Company.objects.get_or_create(
name=row[3].decode('latin-1').encode('utf8'),
description=row[15].decode('latin-1').encode('utf8'),
)
This block is out of a class so it runs when the server is started or basically everytime manage.py is run. Company.objects.get_or_create(...) is trying to run, on the updated database model that can't be created yet. To make the migrations you have to comment this line out, then make the migrations, then it will work.