Django 2.2 AbstractUser and migration issue - django

I extend the Django user model like this:
#core.models
class Institute(models.Model):
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message=institute_phone_help_text)
name = models.CharField(_('name'), max_length=255)
description = models.TextField(_('description'), blank=True)
abbreviation = models.CharField(_('abbreviation'), blank=True, max_length=100)
address = models.TextField(_('address'), blank=True)
phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
websites = ArrayField(models.URLField(max_length=255), verbose_name=_('websites'), blank=True, null=True)
class Meta:
verbose_name = _('institute')
verbose_name_plural = _('institutes')
def __str__(self):
return '{0} ({1})'.format(self.name, self.abbreviation)
class User(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
institute = models.ForeignKey(Institute, on_delete=models.CASCADE)
params = JSONField(_('params'), null=True, blank=True,)
about_me = models.TextField(_('about me'), blank=True,)
With an empty DB each time that I launch ./manage.py makemigrations core it creates always a new migration file
import django.contrib.auth.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20190430_1655'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
I tried different combinations:
./manage.py makemigrations core
./manage.py migrate core
./manage.py migrate
./manage.py makemigrations core
./manage.py makemigrations core
./manage.py makemigrations
./manage.py migrate
It always creates the migration file.
Thanks.
D

if you use AbstractUser model make sure you run makemigrations before migrate.
i had same issue with AbstractUser,
I solved it by deleting the sqlite3 file also all migrations files.
After that i run this two commands :
python manage.py makemigrations
python manage.py migrate
inside your terminal
Let me know if that help!

Related

Rename a field which was Primary Key in models.py

I have a model with the following fields:
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
department = models.TextField(verbose_name="department")
username = models.CharField(max_length=30, unique=True)
emp_id = models.AutoField(primary_key=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
hide_email = models.BooleanField(default=True)
name = models.TextField(verbose_name="employee name")
I want to rename "emp_id" field to "id", as you can see it is the primary key field. Can you please create a migration file for the same?
Thank you
You modify the field to:
class MyModel(models.Model):
# …,
id = models.AutoField(primary_key=True, db_column='emp_id')
# …
If you then run manage.py makemigrations, Django will ask if you renamed the fied:
Did you rename mymodel.emp_id to mymodel.id (a AutoField)? [y/N]
a question you answer with yes.
This will still use the emp_id as the database id. If you want to rename the database column as well, you can just remove the emp_id field, and Django will use the default id field as primary key instead, and you can let Django make migrations the same way.
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('your_app_name', 'name_of_previousmigration_file'),
]
operations = [
migrations.RemoveField(
model_name='modelname',
name='emp_id',
)
]
class ModelName(models.Model):
id = models.AutoField(primary_key=True)
# other fields
Then run python manage.py makemigrations
A message will appear which will tell you to confirm that you want to rename the field emp_id to id. Type y to confirm yes.
Then run python manage.py migrate
In you application directory you'll found migration files.

Can not create db table in django migration

I have 2 apps "app1", "app2" in my django project.
When I ran python3 manage.pymakemigrations, I can see
...
Migrations for 'app1':
...
Migrations for 'app2':
...
But when I ran python3 manage.py migrate, I got error saying
django.db.utils.ProgrammingError: relation "auth_user" does not exist
"auth_user" is db table for app1.User model, also is what AUTH_USER_MODEL refers to.
I tried to run migrate separately. It is fine for app2. But when I run python3 manage.py migrate app1, I got
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
I cannot find a solution for my case, anyone can help?
The user model code:
class User(AbstractBaseUser, Base):
USER_TYPE_CHOICES = (
(1, 'supervisor'),
(2, 'admin'),
(4, 'support'),
)
email = models.EmailField(primary_key=True, max_length=256)
name = models.CharField(max_length=45, null=True)
password = models.CharField(max_length=256, null=True)
last_login = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
user_type = models.PositiveSmallIntegerField(
choices=USER_TYPE_CHOICES,
default=2
)
USERNAME_FIELD = 'email'
objects = UserManager()
class Meta:
db_table = 'auth_user'
app_label = 'admin_portal'
def __str__(self):
return str(self.email)
#property
def is_admin(self):
return self.user_type == 1
#property
def is_active(self):
return self.active
Use this command separately for each app:
python3 manage.py makemigrations app1
python3 manage.py makemigrations app2
Its bad idea but try this. Delete all migration, cache files nd do run makemigrations to each app not entirely.then run the migrate
I had the same error but because I tried modifying the the AUTH_USER during development.
In my case what worked was downgrading django to 2.0, deleted all migrations and had to drop the database.
But it worked.
Then when upgrading to 4.0 had to apply "auth" migration but worked fine.

assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field

I got following error:
assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field )
Here is my Product class code:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
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="shop/images", default="")
def __str__(self):
return self.product_name
What Am I doing wrong?
I have the same error, and i resolve doing that:
1 - Move to trash old migrate
2 - run python manage.py makemigrations
3 - run python manage.py migrate
if your problem persist, try to delete table into a data base ( if you do that, you lost your admin user, you can create another with python manage.py createsuperuser

Can't migrate new models

Hi my code was running smoothly as i was following a tutorial but at a new step while adding new component in the model Order (processing, aprouved, refunbd_requested, refund_granted) the code crashed, the migrations operated but can't migrate i need help please.
my models.py
from django.conf import settings
from django.db import models
from django.shortcuts import reverse
from django_countries.fields import CountryField
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete= models.CASCADE)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
billing_address = models.ForeignKey('BillingAddress',
on_delete= models.SET_NULL, blank=True, null=True)
payment = models.ForeignKey('Payment',
on_delete= models.SET_NULL, blank=True, null=True)
coupon = models.ForeignKey('Coupon',
on_delete= models.SET_NULL, blank=True, null=True)
processing = models.BooleanField(default=False)
aprouved = models.BooleanField(default=False)
refund_requested = models.BooleanField(default=False)
refund_granted = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total(self):
total = 0
for order_item in self.items.all():
total += order_item.get_final_price()
if self.coupon:
total -= self.coupon.amount
return total
The last line of code for the error traceback after the migration, i try python manage.py migrate but i get that at the last line.
File "C:\Users\18094\AppData\Local\Programs\Python\Python37\lib\sitepackages\django\utils\dateparse.py", line 107, in parse_datetimematch = datetime_re.match(value)
The table might contain data that conflicts with the datatype, ie. one of your date fields.
Since this data is not critical, you can remove the data and start over.
assuming your app is named orders
./manage.py migrate orders zero # migrate to 0000, deleting the table
./manage.py migrate orders # migrate forward to current state
This method I am suggesting is a quick but not to recommend for the project in a production environment. You could try this out.
Make sure you add your app in the installed app, delete all your migrations folders, all the pycache folders, as well as the .sqlite file, then run the commands python manage.py makemigrations, python manage.py migrate and then start the server.
You could also run this python manage.py makemigrations app_name if the first command doesn't detect the migration
I hope this is helpful

Django relation "personindustry" does not exist

I have a below model,
class PersonIndustry(DFModel):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
industry = models.CharField(max_length=50, blank=True, null=True)
class Meta:
db_table = ‘person_industry'
My postgres database contains person_industry table.
When I registered this model in admin site it is giving me below error,
ProgrammingError at /admin/apis/personindustry/
relation "personindustry" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM “personindustry"
I am quite confuse why it is searching for personindustry instead of person_industry. Please advise.
I also had this problem recently, what I did is:
# Clear migrations history
python manage.py migrate --fake APP_NAME zero
Then, delete the migrations files and .pyc files except for init.py. Now, make migrations:
python manage.py makemigrations APP_NAME
Now, fake the intial migrate. That will fake the intial table with name personindustry:
python manage.py migrate --fake-initial
*Note:- Feel free to ask. Refs
My meta class was creating problem,
class DFModel(models.Model, metaclass=DFModelBase):
class Meta:
abstract = True
I changed it to default,
class PersonIndustry(models.Model):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
industry = models.CharField(max_length=50, blank=True, null=True)
class Meta:
db_table = ‘person_industry'
It is loading now.