Can not create db table in django migration - django

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.

Related

Django ImageField get username

models.py
def upload_to(instance, filename):
return 'verify/%s/%s' % (instance.user_idx.username, filename)
class UserVerifyImg(models.Model):
user_idx = models.ForeignKey(
User,
db_column='user_idx',
on_delete=models.CASCADE
)
business_type = models.CharField(max_length=255)
image = models.ImageField(upload_to=upload_to)
upload_date = models.DateTimeField(auto_now = True)
class Meta:
managed = False
db_table = 'account_user_verify'
This is my model. but It is showed me error.
account.models.UserVerifyImg.user_idx.RelatedObjectDoesNotExist: UserVerifyImg has no user_idx.
I don't now what is the problem. help me please.
Have you run migrations after changing in your model?
python manage.py makemigrations
Then:
python manage.py migrate
You are actually using the right query instance.user_idx.username the problem is that at the time you assigning the image path(upload_to) the instance is not created,so that means you can not get instance.user_idx.username that is why you are getting that exception.
To solve this problem you can create a foreignkey by doing something like this.
class UserVerifyImg(models.Model):
user_idx = models.ForeignKey(
User,
db_column='user_idx',
on_delete=models.CASCADE
)
business_type = models.CharField(max_length=255)
upload_date = models.DateTimeField(auto_now = True)
class Meta:
managed = False
db_table = 'account_user_verify'
def upload_to(instance, filename):
return 'verify/%s/%s' % (instance.user_verify_img.user_idx.username, filename)
class Image(models.Model):
user_verify_img = models.ForeignKey(UserVerifyImg,on_delete=models.CASCADE)
image = models.ImageField(upload_to=upload_to)
run python manage.py makemigrations
run python manage.py migrate
Note that You have to change your form and your views for this to work if you need more help let me know

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

relation "weather_city" does not exist

When I push my django project to heroku I get "relation "weather_city" does not exist". weather is the name of the app and city is a model.
models.py
from django.db import models
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=25)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'cities'
I think you may have forgotten to make migrations.
heroku run bash
$ python manage.py migrate

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.

Django 2.2 AbstractUser and migration issue

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!