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.
Related
I am having a problem with Django 2.2.7 and postgresql 12 using the command "python manage.py migrate".
When I execute it, the process fails with the following error:
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "clients_clients"
I understand that this error indicates that when a field is used as a foreing key in another table, this field must be unique.
My model clients in Django is:
class Clients(models.Model):
name = models.CharField(max_length=60, unique=True)
document_num = models.CharField(max_length=15)
phone = models.CharField(max_length=15, blank=True)
email = models.EmailField(max_length=30, blank=True)
instagram = models.CharField(max_length=30, blank=True)
address = models.TextField(max_length=100, blank=True)
The model with the foreing key to the field "name" of clients_clients is:
class Budgets(models.Model):
date = models.DateField(error_messages={'null': "You must set a date"})
title = models.CharField(max_length=50, unique=True)
client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, to_field='name')
price = models.DecimalField(default=0, decimal_places=2, max_digits=10)
observations = models.TextField(max_length=200, blank=True)
As is shown above, the field "name" in model "Clients" is set as unique=True. But in spite of that, the error mentioned is shown.
Anyone can help me to understand why?
I could fix the problem.
The problem is as I copied my Django application from an existing installation to a new one, a lot of migration files exist in the app folders.
First, I had to delete all the files inside the "migrations" folders in any app of my Django project (taking care of not delete the init.py file).
Then I ran again the commands:
python manage.py makemigrations
and
python manage.py migrate
Now, everything works fine.
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.
We have two Django models:
class Project(models.Model):
project_title = models.CharField(max_length=30)
owner = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING)
class User(models.Model):
usernmae = models.CharField(max_length=50)
active_project = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING, related_name='current_project')
I have a user with object (with id say 692). And this user created a project with id=12345, therefore these owner field will get have this particular referenced.
I want to delete that user. But it shows error that
delete on table "app_user" violates foreign key constraint
This is expected as on_delete=models.DO_NOTHING, was set. One way I found out was using on_delete=models.CASCADE.
Question: How should I go about deleting the user (692) without changing the model definition(having to re-run migration)?
Doing it manually by deleting the project first, leads to the same foreign-key error, as owner field is User object.
How to handle this mutual foreign key relationship while deleting, as deleting any one of those two throws the foreign-key exception?
Update
Some correction in the model definition username is the field name instead of usernmae (typo). And the foreignkey for project is Project not the User model.
class Project(models.Model):
project_title = models.CharField(max_length=30)
owner = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING)
class User(models.Model):
username = models.CharField(max_length=50)
active_project = models.ForeignKey(Project, null=True, on_delete=models.DO_NOTHING, related_name='current_project')
IF you really don't want to make a migration (any specific reason?) and if you are ok with doing this manually this time. Then you have two options:
Go into the admin panel and manually change the User field in the project instance to a different user or to NULL. Now you should be able to delete the User instance since it's not referred anymore into the project.
If that worked, you can then delete the project instane as well.
Curios if this will work, let me know!
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
Here's the code:
class community(models.Model):
communityName = models.CharField(max_length=280)
communityID = models.BigIntegerField(null=True,blank=True)
icon = models.CharField(max_length=400)
def __str__(self):
return self.communityName
class team(models.Model):
date = models.DateField()
startTime = models.TimeField()
teamName = models.CharField(max_length=280)
community = models.ForeignKey(community, on_delete=models.CASCADE, default=None)
I've done a lot of reading on this and it makes sense that I'm supposed to set null and blank to true to prevent this error however when I attempt to migrate the models I still get the following error thrown:
django.db.utils.IntegrityError: NOT NULL constraint failed: scheduler_team.community_id
I don't know anything about database management and this is the first project I've attempted to do that has a database involved so an ELI5 would be very much appreciated thank you!
Make it like this in your team model:
community = models.ForeignKey(community, on_delete=models.CASCADE, blank=True, null=True)
This is the proper way to make it nullable.
When you specify default=None, Django ORM does not know if this field is nullable or not.
community_id is the field in team model and it is (though syntactically implicit) used to refer community model by the foreign key in team model, and that field was set as not nullable, so that generates IntegrityError, if not set.