Wednesday 24 June 2020

In Django Shell I can see the Object but I can't Access it.

A simple one this but I couldn't find the answer with a Google search so I thought I'd list it here. 


What I have is a Profile object that links to my User object.  And I'm trying to get the 'image' data from it. 

Using Shell this is what I was doing 

python manage.py shell

from users.models import Profile
profile = Profile.objects.filter(user=1)
profile.image

Which would return me the message.

 'QuerySet' object has no attribute 'image'

However I know its there because when I run


profile.values() 

I can see it.  

The answer is straight forward and you need to do the following to call the specific item that you need. 

profile = Profile.objects.filter(user=1).first()
You'll then be able to user 'profile.image' to return the data.


Wednesday 17 June 2020

django.db.utils.IntegrityError: The row in table ‘%’ with primary key '1' has an invalid foreign key: %.user_id contains a value '1' that does not have a corresponding value in auth_user.id.

This is on a Django / Wagtail project.  Although I think the issue is relevant only to the Django side of it here. 

I was getting this error when running some tests on my APP .

python3 manage.py test tasks



The error :
django.db.utils.IntegrityError: The row in table ‘%’ with primary key '1' has an invalid foreign key: %.user_id contains a value '1' that does not have a corresponding value in auth_user.id.


The offending code :


django models.ForeignKey(User, on_delete=models.CASCADE, default=1)


Here's what I searched when looking for an answer:

Django how to add a default user id to model


Django model foreignKey user pass in default user



Django does not have a corresponding value in auth_user.id


I tried a few different methods to resolve including removing all my migration file and running the migrate commands again .


python3 manage.py makemigrations


Python3 manage.py migrate



What I found worked though was to change my code to the following line ( and then run the above migration commands again )



user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)

Wednesday 3 June 2020

Wagtail: admin KeyError at /admin/

I recently saw this error after playing around with Page Model Classes.   

To fix this I worked out which Class was at fault and had to remove it and all mentions of it in the 'Migrations' folder.  

Once I did that I could run the following commands again and had regained access to my /admin/ folder 

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

I also renamed my Class to not cause any other possible conflicts.