"no such column: id" Django AbstractUser model - python

I am trying to migrate, and view the admin page. both makemigrations and migrate passed, yet when i go to the admin url it reads this: "django.db.utils.OperationalError: no such column: social_app_user.id"
And once i create an id field, it changes to "django.db.utils.OperationalError: no such column: social_app_user.password"
I was under the impression that the AbstractUser model included all the default user fields, not sure about the primary key, but regardless.
Please help, thanks!
Note: the 'id' field in this models.py file was added after i got the error.
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
class User(AbstractUser):
is_verified = models.BooleanField(default=True)
id= models.AutoField(primary_key=True, null=False)
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
f"{self.username} {self.email}"
return
class main_feed(models.Model):
content= models.CharField(unique=True, max_length=255, default='', null=False)
poster = models.ForeignKey('User', related_name='author', on_delete=models.CASCADE, to_field='username')
likes = models.IntegerField(default=0, null=False)
favorites = models.IntegerField(default=0, null=False)
date_posted = models.DateTimeField(auto_now=True)
def __str__(self):
f"{self.content} {self.likes} {self.poster} {self.date_posted}"
return

It turns out I had to restart my entire application and run startapp again.
This time i added the user model and set up the settings and admin file BEFORE the very first migration. then everything works dandy. But I have no idea why this is the case, shouldnt the migration update and override the default user model?
anyways the question is answered now.

Related

unique_together = (("name", "added_by"),) in Django model gives IntergretyError at/admin instead of Validation Error

I want to show a validation message like "This Project already exists" in my django admin whenever i create a project with same name.
I keep getting an IntegrityError at my Name. Isn't Django supposed to validate this and give an ValidationError if I use unique_together=((,)) in my model? Or do I have to Try and Catch the IntegrityError myself?
Also i have made two users and gave permissions to them from main admin user. so i want that one user1 cannot have projects with same name like proj1 while the user2 can have name of project as proj1.
Can anyone tell me a best practice for validating unique users inside a form/model.
models.py
class Project(models.Model):
name = models.CharField(max_length=200)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, default=None)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
unique_together = (("name", "added_by"),)
def __str__(self):
return self.name

NOT NULL constraint django

I am trying to create a cart model using ForeignKey relation with User.
My mall/models.py:
from django.db import models
from django.contrib.auth.models import User
class products(models.Model):
image = models.ImageField(upload_to='products/', blank=True)
name = models.CharField(max_length=100)
detail = models.TextField(max_length=100, verbose_name='detail of product')
price = models.FloatField()
def __str__(self):
return self.name
class cart(models.Model):
item = models.OneToOneField(products, on_delete=models.CASCADE)
user = models.ForeignKey(User, null=True, blank=True, default=None, on_delete=models.CASCADE)
def __str__(self):
return self.item.name
I am getting a error like this:
django.db.utils.IntegrityError: NOT NULL constraint failed: new__mall_cart.user_id
whenever I am trying to migrate it. Its showing the same error if I am migrating the products class alone as well
.
I have provided null=True as well as blank=True and the superuser is created with the name of admin. What is issue here?

Users as foreign key in Django

I have the below in my models.py file:
class Film(models.Model):
title = models.CharField(max_length=200)
director = models.CharField(max_length=200)
description = models.CharField(max_length=200)
pub_date = models.DateField('date published')
class Comment(models.Model):
film = models.ForeignKey(Film, on_delete=models.CASCADE)
body = models.CharField(max_length=200)
When I logged into Django admin I added some films, and then added some comments, selecting which film object the comment related to. I then created a couple of users via the admin panel also.
I would like my relationships to be:
Film can have many comments / Comments belong to film
User can have many comments / Comments belong to user
I think, like with comments and films, I just need to define user as a foreign key to comment. I am struggling to do this. I am working through the Django tutorials but I can't see the tutorials covering how I can link other tables to the user.
I thought I would be able to do something like this:
user = models.ForeignKey(User, on_delete=models.CASCADE)
While importing User like this:
from django.contrib.auth.models import User
The result at the moment is if I keep user = models.ForeignKey(User, on_delete=models.CASCADE) I get err_connection_refused
Maybe have you changed your default user model in the settings?
Instead of using User directly with the the Foreign key, you should use user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) in your Comment Model, as follow
class Comment(models.Model):
film = models.ForeignKey(Film, on_delete=models.CASCADE)
body = models.CharField(max_length=200)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
You need to apply migrations to be able to add user to Comment,
python manage.py makemigrations
python manage.py migrate
if at the moment that you are applying migrations, shell shows a message telling You are trying to add a non-nullable field 'user' to comment without a default
You have 2 Options
Skip migrations and add a default value to the field in the models or set the attribute as nullable, whatever else that you need
ie
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
and apply migrations again
Or select a default value to the new field, should be an id of an existing user in databse
This is because django should populate existing records in database, if exist
Use "settings.AUTH_USER_MODEL".
So, import "settings" from "django.conf", then use "settings.AUTH_USER_MODEL" as shown below:
from django.db import models
from django.conf import settings # Here
class Comment(models.Model):
film = models.ForeignKey(Film, on_delete=models.CASCADE)
body = models.CharField(max_length=200)
# Here
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Django migrate unique field between models with data

Let's assume I have this models structure:
class User(AbstractUser):
first_name = models.CharField(max_length=40, blank=True)
last_name = models.CharField(max_length=40, blank=True)
class UserProfile(models.Model):
uuid = models.UUIDField(unique=True, null=False, default=uuid4)
user = models.OneToOneField(User)
I would like to merge UserProfile into User model, like this:
class User(AbstractUser):
first_name = models.CharField(max_length=40, blank=True)
last_name = models.CharField(max_length=40, blank=True)
uuid = models.UUIDField(unique=True, null=False, default=uuid4)
Most important thing is to migrate existing uuid from UserProfile model to new User.uuid (unique) field. How should that be managed in django > 1.7 migrations ?
First, add the uuid field to the User model. Create a migration.
Then, create a data migration and add a RunPython operation to call a function that copies the data from the old to the new models. Something like:
def copy_uuid(apps, schema_editor):
User = apps.get_model("myapp", "User")
# loop, or...
User.objects.update(uuid=F("userprofile__uuid"))
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.RunPython(copy_uuid),
]
Once you've migrated and are sure that everything worked, you can delete the UserProfile model in another migration.

Django ForeignKey to AbstractBaseUser

I'm trying to set up an app that will handle reviews about registered users. So in my Review model, I want to have a ForeignKey to my User model.
I'm using a custom user profile that looks like this:
#In /profiles/models.py
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
company = models.CharField(default="", max_length=200)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['company']
I have included it with settings.py AUTH_USER_MODEL = "profiles.MyUser". It works fine with registration, creating users etc. So I know its working.
In my review model I write the following:
class Review(models.Model):
company = models.ForeignKey(settings.AUTH_USER_MODEL)
reviewer = models.ForeignKey(Reviewer)
rating = models.IntegerField(default=0)
review = models.TextField()
pub_date = models.DateTimeField('date published')
Instead of settings.AUTH_USER_MODEL I have also tried writing profiles.MyUser, 'profiles.MyUser' and MyUser.
I can successfully use the python manage.py makemigrations reviews command. But when I do python manage.py migrate I get errors no matter what version I use above.
The error I get is the following:
ValueError: Lookup failed for model referenced by field reviews.Review.company: profiles.MyUser
nejc92 comment was correct. I had migrated my database earlier before I set AUTH_USER_MODEL for the first time.
I removed my whole database and created new migrations for all apps and migrated everything again from scratch. It then worked.
Sounds like a bug(?) to me.

Categories

Resources