0

Every time i try to delete a post i keeping getting this error, but my delete button use to work before. I think it has something to do with the on_delete attribute but i changed its value a few times and it still did not work.

//models.py

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


User = settings.AUTH_USER_MODEL

class PostManager(models.Manager):
    def search(self, query):
        qs = self.get_queryset().filter(title__icontains=query)
        if qs:
            return qs
        return None

    def get_by_id(self, id):
        qs = self.get_queryset().filter(id=id)
        if qs.count() == 1:
            return qs.first()
        else:
            return None     


# Create your models here.
class PostModel(models.Model):
    user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    message = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    likes = models.ManyToManyField(User, blank=True, related_name='post_likes')


    def __str__(self):
        return self.title

    objects = PostManager()

    def get_total_likes(self):
        return self.likes.count()   

    def get_absolute_url(self):
        return reverse("birdpost:detail", kwargs={"id": self.id})

    def get_like_url(self):
        return reverse("birdpost:like-toggle", kwargs={"id": self.id})

    def get_delete_url(self):
        return reverse("birdpost:delete_post", kwargs={"id": self.id})

//views.py

def del_post(request, id):
    obj = get_object_or_404(PostModel, id=id)
    if request.user != obj.user:
        print("Ooh no looks like this post is not yours... ")
    else:
        obj.delete()

    return redirect("home")

Environment:

Request Method: GET Request URL: http://localhost:8000/post/4/delete

Django Version: 2.2.1 Python Version: 3.6.8 Installed Applications:

['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'accounts',
 'birdpost',
 'search']

Installed Middleware:

['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in _commit
  240.                 return self.connection.commit()

The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/grey/Desktop/python/birds/src/birdpost/views.py" in del_post
  104.      obj.delete()

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/models/base.py" in delete
  919.         return collector.delete()

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/models/deletion.py" in delete
  318.                             sender=model, instance=obj, using=self.using

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/transaction.py" in __exit__
  240.                         connection.commit()

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in commit
  262.         self._commit()

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in _commit
  240.                 return self.connection.commit()

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "/home/grey/Desktop/python/birds/virtualenv/lib/python3.6/site-packages/django/db/backends/base/base.py" in _commit
  240.                 return self.connection.commit()

Exception Type: IntegrityError at /post/4/delete
Exception Value: FOREIGN KEY constraint failed
Grey Hack
  • 9
  • 1
  • 6
  • 1
    Please post the full stack trace. – kungphu Jul 03 '19 at 22:39
  • Its's there now. – Grey Hack Jul 04 '19 at 08:02
  • What if you also add the `on_delete=models.CASCADE` arg to your `likes` field? – olinox14 Jul 04 '19 at 08:06
  • The like field is a ManyToManyField field i get an error every time i put a on_delete on there: TypeError: __init__() got an unexpected keyword argument 'on_delete' – Grey Hack Jul 04 '19 at 08:24
  • I don't think you can put an on_delete argument on a ManyToManyField. For a ForeignKey you have to explicitly specify that it can be null when initially unpopulated but the same doesn't apply to an m2m relation so an on_delete would be unnecessary. Maybe this post would help? https://stackoverflow.com/questions/54655757/django-db-utils-integrityerror-foreign-key-constraint-failed – Sharpfawkes Jul 04 '19 at 08:33
  • It didn't bring me any further. – Grey Hack Jul 04 '19 at 09:16
  • Is the error coming on every post deletion? – Technocrat Jul 04 '19 at 15:11
  • Yes it's comming from every post deletion, even when i try to delete it in django administration. – Grey Hack Jul 04 '19 at 16:00

2 Answers2

1

I removed the default=1 like @Na'aman Hirschfeld said, and deleted all of my migrations and my database. And now it's working fine.

Grey Hack
  • 9
  • 1
  • 6
0

Try removing the default=1. I don't know if setting a default value without a choice field is the way to go.

  • Don't know if it worked but i removed the default=1, and deleted all of my migrations and my database. And now it's working fine. – Grey Hack Jul 05 '19 at 09:43