I wanted to extend the Base Abstract User Model within Django to have some other Fields:
class Student(AbstractUser):
birth = models.DateField(default=datetime.date.today)
street = models.CharField(max_length=20)
street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)])
city = models.CharField(max_length=20)
province = models.CharField(max_length=20)
code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))])
address = str(street) + str(street_number) + str(city) + str(code) + str(province)
def __str__(self):
return f'Adresse: {self.address}'
I added this into my settings.py file:
AUTH_USER_MODEL = 'mainApp.Student'
But I get an Error saying there is no such table "Student" when trying to load /admin/.
I have made all the migrations using:
python manage.py makemigrations mainApp
python manage.py migrate mainApp
Error:
OperationalError at /admin/
no such table: mainApp_student
If y'all need any more infos, please comment!
Try in first time to run:
python manage.py makemigrations
python manage.py migrate
Without put the app name to migration process
You cannot define "address" like this. Database column is not for string concatenation of other columns, nor any calculation. It can cause error.
Related
I have a class called Difference in my script "myProject.models.difference.py" that is:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
And in my script "myProject.admin.scenario.py" I have the corresponding admin class:
class DifferenceAdmin(admin.ModelAdmin):
list_display = ("comparator","summary",)
But I need to add two fields more to my Class Difference:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
diff_class = models.CharField('diff_class',max_length=1000)
diff_field = models.CharField('diff_field',max_length=500)
After that I read the next error: "no such column: myproject_difference.diff_class".
But if I comment the new fields diff_class, diff_field of this way:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
#diff_class = models.CharField('diff_class',max_length=1000)
#diff_field = models.CharField('diff_field',max_length=500)
Then the error disappears. ¿What must I do in order to add the new fields?
You need to do a database migration. Save your model:
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
diff_class = models.CharField('diff_class',max_length=1000)
diff_field = models.CharField('diff_field',max_length=500)
Then do the following two manage.py commands:
$ python3 manage.py makemigrations
$ python3 manage.py migrate
You will need to do this every time you make changes to models.py
After adding fields to your model, you must make migrations to add the columns to your database
run these two commands
python manage.py makemigrations
python manage.py migrate
In the myProject.models folder, is there an __init__.py file? Inside of it, you'll need this:
from .difference import *
When you have models in a different .py file than models.py, you need to import them in the init.py file, or else the Django app will not know that it's there.
When you did python manage.py makemigrations did it create migrations files in the migrations folder?
The solution is to write a defoult value for diff_class and diff_field. When you run python manage.py makemigrations it appears a warning saying you need defoult values.
So I write
class Difference(models.Model):
comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE)
summary = models.CharField('summary',max_length=900000)
diff_class = models.CharField('diff_class',max_length=1000,default = 'class')
diff_field = models.CharField('diff_field',max_length=500, default= 'field')
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'm using Django to build an ecommerce webapp. I wrote this code in models.py
from django.db import models
# Create your models here.
class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="")
subcategory = models.CharField(max_length=50, default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateField()
image = models.ImageField(upload_to='mainShop/images', default="")
Then, I performed makemigrations using
python manage.py makemigrations
which produced the following
D:\Projects\PyCharm Projects\VeroniCart\home>python manage.py makemigrations
No changes detected
Then I did
python manage.py migrate
This gave me the error:
ValueError: invalid literal for int() with base 10: ''
I'm also attaching a log file with the complete error.
Any help appreciated!
Issue solved. All I did was I deleted all files from my app's migrations directory (except migrations/init.py) and deleted the database file db.sqlite3 from the project directory.
Then I repeated the previous steps (makemigrations and migrate).
Django again created all migrations files and a new db.sqlite3 file, so this worked for me.
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));
While I save UserProfile into a database,
there's an error "UserProfile has no column named gender error".
Here's my models.py
""" UserProfile : user information """
class UserProfile(models.Model):
# User basic inherits : username, password, email
user = models.OneToOneField(User)
# Profile information
nickname = models.CharField(max_length=63, unique=True, null=False)
url = models.URLField(blank=True, null=True)
birth = models.DateField(null=True) # TODO change null = false
gender = models.CharField(max_length=15, null=False)
nation = models.CharField(max_length=63, null=True)
region = models.CharField(max_length=63, null=True)
description = models.TextField(blank=True, null=True)
# ImageField: http://goo.gl/ZQEG4e
avatar = models.ImageField(upload_to='/avatar/')
# Foreign Keys
tag = models.ManyToManyField(TagCloud)
and while I tested it from ./python models.py shell I typed
> from UserAndPlace.models import *
> u1 = User.objects.get(username="user1")
> u1.username
u'user1'
> p1 = UserProfile(user=u1, gender="female")
> p1.user.username
u'user1'
> p1.gender
u'female'
> p1.save()
OperationalError Traceback (most recent call last)
<ipython-input-9-e08e160cd285> in <module>()
----> 1 p1.save()
....
OperationalError: table UserAndPlace_userprofile has no column named gender
I did python manage.py syncdb and also check errors with python manage.py sql UserAndPlace
How can I fix this errors?
Thanks for your help in advance.
syncdb will not create or modify columns if they already exist in the database. If you already had the model and then you added the gender column, running syncdb will not do anything.
You need to drop the table and re-create it again. If you are using sqlite, simply delete the database file and run syncdb.
If you are using another database, run manage.py sqlclear yourapp and this will give you the SQL you need to execute to reset the tables for the app yourapp (make sure you replace yourapp with the name of the application that has the profile model).
Then, run syncdb again to recreate your models.
Have you done a python manage.py syncdb after you made any changes to your model? This error usually happens when the model and the database are out of sync.