Django ForeignKey Constraint Failed error
Asked Answered
A

2

6

I am creating a simple blog site with multi-user facility using django framework. In my project, If the admin deletes any user, all of that user's blogs should not be deleted, I've tried using

models.ForeignKey(django.contrib.auth.models.User,on_delete=models.CASCADE)

but it obviously deletes all the blogs if the admin deletes the user. Can anyone help me please? Thank in advance...

Acrospire answered 8/12, 2018 at 11:11 Comment(1)
have you tried using SET_NULL instead of CASCADEChowchow
U
12

This is due to the on_delete=CASCADE. That means that if the object to which the ForeignKey refers is deleted, then it should delete the referring object as well. Such CASCADE can thus result in a large amount of objects that get deleted, since the deletion of objects can in fact trigger other deletes, and so on.

There are several options, listed in the documentation:

  1. CASCADE: delete referring objects;
  2. PROTECT: do not allow to delete the user given there are objects that refer to the user;
  3. SET_NULL: set to NULL (None in Python), in that case, one has to set null=True in the ForeignKey(..) constructor;
  4. SET_DEFAULT: sets the ForeignKey back to the default=... value;
  5. SET(..): set the ForeignKey to some value that is passed to the SET(..) constructor (one can also use a callable);
  6. DO_NOTHING: here we keep a reference, but some database backend will not allow that, since these check FOREIGN KEY constraints.

So we can for example use SET_NULL, and thus set the author to NULL/None in case we delete the author:

from django.db import models
from django.conf import settings

class Post(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        on_delete=models.SET_NULL
    )
    # ...

It is also better to use settings.AUTH_USER_MODEL, since if you later change the User model, this will automatically change the reference to the new model.

Ury answered 8/12, 2018 at 11:21 Comment(2)
Nope, It's working as desired. Now, if I try to add a blog from the admin panel, I'm getting this error, AttributeError at /admin/blogs/blog/add/ 'NoneType' object has no attribute 'username'Acrospire
@KamleshGupta: can you share your view? If the author is set to None, then obviously, it has no username anymore.Ury
G
1

I suggest you to run makemigrations and migrate again because you may have deleted models and tried to delete users. I hope it helps because I have solved my issue like this:

python3 manage.py makemigrations
python3 manage.py migrate
Giaour answered 8/3, 2022 at 11:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.