Why am I getting an integrity error django? - python

I am building a django web app with a custom user model. At the end of the sign up process when I submit the form an integrity error occurs.
Here is the error:
Exception Type: IntegrityError
Exception Value: NOT NULL constraint failed: accounts_user.job_history_id
This error indicates that the field in the custom user model named job_history cannot be null. However such a field does not even exist.
Here is my custom user model:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
avatar = models.ImageField(blank=True, null=True)
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username", "password"]
def __str__(self):
return "#{}".format(self.username)
def get_short_name(self):
return self.username
I have no idea what this error is referring to and why it is occurring. I added the field named job_history at a previous point but have since deleted it and updated the database accordingly. This error only began to occur when I was fiddling around with the Job and User models in order to achieve a field capable of storing the users previously completed jobs. Further details are available in this stackoverflow questions.
Why is the integrity error occuring and how do I fix it?

The error says that your job_history field is still in the database and for some reason your migrations didn't work. So you need to look why your migration didn't work. You can try doing fake initial migration:
python manage.py makemigrations app_name
python manage.py migrate --fake-initial
I'm quite sure this should help, but if this also doesn't help you always can go directly to your DB and delete the job_history_id column from DB

Related

Why leads deletion of UUIDField to Django SystemCheckError

I've been building a Django website and included a UUID field "customer_id" in my initial "Customer" model. Finally, I decided to drop it. But when I try to delete it from my models.py, Django throws
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'.
Here is the code of models.py
from django.db import models
import uuid
# Create a base model to make sure we keep track of creation and edits
class ModelBaseClass(models.Model):
date_created = models.DateTimeField(auto_now_add=True, null=True)
date_modified = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
# Create your models here.
class Customer(ModelBaseClass):
customer_id = models.UUIDField(default=uuid.uuid4, #this is the field i try to drop
editable=False,
unique=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
What I tried so far:
I suspect that this could be related to existing data or some other dependencies. So...
I deleted the sqlite database, deleted all migration files and ran
"python manage.py makemigrations" and "python manage.py migrate".
I ran python manage.py flush.
I also tried to change the editable=False to editable=True and migrate before dropping,
but it didn't change anything.
It's perhaps also worth mentioning that my "Customer" model a relation to another model.
Could someone explain me why Django is preventing me from deleting this field and how to resolve this?
Thanks! :)
Could someone explain me what's going on and how to resolve this?
As the error says, you have a model admin named CustomerAdmin. Indeed:
<class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'.
For the readonly_fields, it lists the customer_id, but since that field is no longer available, it raises the error.

NOT_NULL contraint failed when adding foreign key to model in django

I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error while using
python manage.py migrate
. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key.
here's the code :
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]
here's the error :
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id
Your issue is that that there are existing notes in the database that do not have a author_id field, but you have not set a default value and neither allowed to to be kept blank. Thus it's a IntegrityError to add the field.
You can solve this in 2 ways:
Allow the field to be blank
Delete the last migration in your migrations folder
Edit the author field like this:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
Run makemigrations and migrate
Set a default value for the field
Delete the last migration from the migrations folder. You can also edit it but simply deleting it is easiest
Run makemigrations again
During make migration, it will prompt you if you want to provide a default value for the field. Select "Provie a one of value for now"
Type models.User.objects.all().first() or alternatively some other "defalt" author for existing notes
Run migrate
You can also solve the problem by removing all existing notes from the database

(django.db.utils.OperationalError: near ")": syntax error) while creating custon django user model

So i have been racking my beain for literal hours trying to create a simple user model.
I believe Abstractbaseuser creates default id, email, and password columns, and I added a couple more fields.
I also added the AUTH_USER_MODEL into settings.py so I'm pretty sure all the set up should be done to at least be able to run the migration.
makemigrations works and passes, but migrate gives me that error every time.
So I think, I set up the model correctly(hopefully) but there has to be something I'm missing.
from django.contrib.auth.models import AbstractBaseUser
from django.db import models
class User(AbstractBaseUser):
username = models.CharField(unique=True, max_length=64, default='')
email = models.EmailField(unique=True, max_length=64)
is_verified = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
f"{'username'} {'email'}"
return

Not Null Constraint Failed - null=True already set

I am changing my register model so that there is a foreign key referencing a location. What I want to achieve, is to have a relationship where the Register model can have 0 to many locations.
Originally I set a manytomany field which I realised was a mistake as it gives each Register all of the locations in existence. I just want a subset for each Register.
My model now looks like:
class Register(AbstractBaseUser, models.Model):
username = models.CharField(max_length=20,default='',blank=True)
password = models.CharField(max_length=80,default='',blank=True)
email = models.CharField(max_length=255,default='',blank=True)
#Added 2nd May
#locations = models.ManyToManyField(Location)
#3rd May change to foreign key
locations = models.ForeignKey(Location,on_delete=models.CASCADE, blank=True, null=True, default='')
USERNAME_FIELD = 'username'
The model referenced is:
class Location(models.Model):
locationname = models.CharField(max_length=80,default='',blank=True)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')
When I try to migrate I get the error below. I have ran makemigrations and if I run it again it states there are no changes.
"NOT NULL constraint failed: register_register.locations_id"
I have been searching other posts and it suggested adding the null=True argument which I have added, but I still get this error. I can't find any posts where this has been done and it still gives this error.
Purging the data from the database using manage.py flush allowed me to re-migrate the projects.
I realised that I had made a mistake with the relationship and had the Foreign key on the wrong table, it needed to be on location so that was fundamentally the issue.

Python Django OperationalError no such column model.id

When trying to access my model via the Admin webpage using Django, I get an Operational Error stating "no such column: model_name.id"
I did my migrations and all but I am still getting the same error.
I assume I am getting this error because I had to change the name of my model. Since, I had to delete my database and migrations and had to re migrate all of my changes.
I originally got the error of not having a table built so I used some SQL to build the table and now I am stuck with a missing column under the name "id". Thanks in advance.
My models:
class PersonalUse(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone_number = models.IntegerField()
verification = models.IntegerField()
messages = models.BooleanField(default=False)
message_sent = models.BooleanField(default=False)

Categories