#Issue with Foreign Key Constraint in Custom User Model in Django

1 messages · Page 1 of 1 (latest)

barren kiln
#

I have created a custom user model that extends AbstractUser. The model includes a profile_image field, which is an ImageField. When I upload an image via the Django admin interface and click save, I encounter the following error:

django.db.utils.IntegrityError: FOREIGN KEY constraint failed

Model Code:

from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    bio = models.TextField(blank=True)
    profile_image = models.ImageField(upload_to='profile_images/', blank=True)

This is my first migration in a new Django app, no other models exist

near orchid
barren kiln
near orchid
#

or tinkered with db manually>

barren kiln
near orchid
#

try running python manage.py shell

#

Then import your model and try to create or change an instance

#

And see if there is an error and if it has more details

barren kiln
near orchid
#

update is limited to fields, try with user.save()

#

I don't see problems with the code, so we want to investigate what FK it's complaining about

barren kiln
#

I could update to a new image without any problems```py
In [7]: user.profile_image = profile_image

In [8]: user.save()

near orchid
#

Hm, probably issue is with the admin

#

Have you run migrate before adding your User model?

barren kiln
#

I must have, I don't remember

#

I deleted migration files, db.sqlite3 and started over again

#

I made the first initial migration without my model: ```py
python .\manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
...

#

When I tried a second migration with my custom user, I get an error

near orchid
#

that's the whole point, you must NOT do migrations before swapping user model

#

it's not designed to be changed after initial

#

It's possible but it's much harder

#

You must setup user model first and init db with it, so it never knows about default one

#

Ortherwise it build relationships with old model and likely source of your error

barren kiln
#

Thanks! Migrating from the start was it

#

I have a slight problem in displaying the image. This is my settings.py extract: py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') part of html: html <img src="{{ request.user.profile_image.url }}" alt="profile pic"> The image isn't displayed on my page. On inspecting the source, I found the image url: nim http://127.0.0.1:8000/media/profile_images/main_TeNMFjY.png When I open it separately I get an error: ```m
Page not found (404)

near orchid
#

Django doesn't serve media files by default (and not supposed to serve files in deployment)

#

You can add a separate line to urls during development