table UserAndPlace_userprofile has no column named gender - python

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.

Related

Error: no such table when extending Abstract User Model

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.

error in migration with legacy database in Django

I'm working on creating a filter in django where the options displayed are coming from a new column in the database. It turns out that this column was created directly in the database and so that it could be displayed in my template, I need to capture this field in the models.
After some research, I found in django's own documentation a function called "inspectdb" that is called by manage.py. So far so good, after executing the function, the database fields are added to my project so that they can be directed to their corresponding app.models.
The documentation indicates that I must perform a python manage.py migrate for the sync to complete, this snippet of code is where the problem happens. When performing the migrate, I get the following error: "django.db.utils.ProgrammingError: relation "crontabmanager" already exists"
The "crontabmanager" table actually exists in my database, but it is not changing at this time.
Some actions were taken to try to get around this problem, for example:
I tried to ignore the migration and use the new field directly in the system, but it returns stating that the new column does not exist
Delete the migration file and create a new "makemigration"
Delete the "crontabmanager" table from the database for django to recreate through the ORM
Changing models.py properties to ignore changes made
Below is the snippet of my current models.py code:
from django.db import models
class Crontab(models.Model):
client = models.TextField('Cliente', blank=True, null=True)
script = models.TextField('Nome do script', primary_key=True)
schedule_code = models.TextField('Codigo Crontab', blank=True, null=True)
crontab_command = models.TextField("Comando", blank=True, null=True)
log = models.TextField("Log", blank=True, null=True)
class Meta:
verbose_name = 'Crontab'
verbose_name_plural = 'Crontab'
db_table = "crontabmanager"
class Trello(models.Model):
id_card = models.TextField('ID do Card', primary_key=True)
card_name = models.TextField('Nome do Card', blank=True, null=True)
due_date = models.TextField('Data de conclusão', blank=True, null=True)
list_name = models.TextField('Nome da lista', blank=True, null=True)
tipo_corte = models.TextField('Tipo do corte', blank=True, null=True)
cortes = models.TextField('Numero de cortes', blank=True, null=True)
unidade = models.CharField(max_length=200, blank=True, null=True) #new field added
class Meta:
db_table = "trello_pta"
error when running python manage.py migrate
$ python3 manage.py migrate
Operations to perform:
Apply all migrations: accounts, admin, auth, contenttypes, core, sessions, users
Running migrations:
Applying core.0002_initial...Traceback (most recent call last):
File "/home/file_names/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 87, in _execute
return self.cursor.execute(sql)
psycopg2.errors.DuplicateTable: relation "crontabmanager" already exists
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
...
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "crontabmanager" already exists

Cannot alter tables after Django migration in posgres DB

I really need to know why in the world we cannot change the column types after we do the migrations to Postgres DB.
I already created my models by python manage.py makemigrations then do migrate. Everything looks fine and tables are created on the postgres DB.
class test_API(models.Model):
IDnumber = models.IntegerField(null=False, blank=False)
State = models.CharField(max_length = 256, null = True)
Exlcludmethod = models.CharField(max_length=256, null=True)
class test_API_2(models.Model):
Idnumber = models.Foreignkey(test_API, max_length = 256, blank=False, null = False)
value = models.CharField(max_length=128, default="")
last_updated = models.DateTimeField(auto_now=True)
Lets say we want to make change to IDnumber column from Integerfield to Charfield.
class test_API(models.Model):
IDnumber = models.CharField(null=False, blank=False)
State = models.CharField(max_length = 256, null = True)
Exlcludmethod = models.CharField(max_length=256, null=True)
and run the python manage.py makemigrations again
return self.cursor.execute(sql)
psycopg2.errors.DuplicateTable: relation "test_API" already exists
How can we modify/change column types and do migrations. What is the proper way of doing this ?
Using
Django:Django==4.0.3
Python = 3.9.1
Posgresql = 2.9.3
Django migrations using RunPython to commit changes
django 1.7 migrate gets error "table already exists"
It seems like you want to drop the link to test_API in test_API_2. If you want to be able store 'abcd' type strings, and not try to keep anything from the relation previously created by the ForeignKey field, then I believe you need to do this in a two step process.
First step would be to remove (or comment) the IDNnumber field, make migrations, then add it back with a new type of field.
The IDNumber field was more than an integer field, it has an indexed relation to test_API, so you need to sever that first by removing the field, then create a new field with identical name.

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 south - column none does not exist

i am failing to migrate using south. the problem is this:
i created a model, then i did schemamigration app --auto, then migrate app, it was fine. then later on, i added another field to this model and then did again those two commands, but now it is saying, column 'None' doesnot exist. i think, it was because i had a foreignkey field and that didnot have default value, i added some empty string default value, then did the commands again, it said the same error, now i deleted the model and did schemamigration and migrate app, but it still keeps giving this error.
this is my model:
class User(models.Model):
registerdate = models.CharField(max_length=400,default='')
vorname = models.CharField(max_length=100,default='')
nachname = models.CharField(max_length=100,default='')
email = models.EmailField(max_length=100,default='')
strasse = models.CharField(max_length=100,default='')
hausnr = models.CharField(max_length=100,default='')
stadt = models.CharField(max_length=100,default='')
land = models.CharField(max_length=100,default='')
##for confirm mails - the hash
unique = models.CharField(max_length=400,default='')
kennwort = models.CharField(max_length=200,default='')
username = models.CharField(max_length=200,default='')
locations = models.CharField(max_length=10, default='')
can someone please help me?
thanks a lot
field_name = models.CharField(max_length=400, blank=True)
You will have to edit your migration file, or regenerate it with a valid default. Your assumption of the invalid default is correct.

Categories

Resources