Реализовал систему лайков и добавление в избранное. Когда ставлю лайк, появляется ошибка "IntegrityError at /like_topic/1/FOREIGN KEY constraint failed". Код прилагаю ниже.
models.py
class Topic(models.Model):
class NewManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
options = (
('published', 'Published'),
)
name = models.CharField(max_length=200)
category = models.ForeignKey(
Category, verbose_name="Category", on_delete=models.SET_NULL, null=True, related_name='topic'
)
content = models.TextField()
likes = models.ManyToManyField(User, related_name='topic_likes', default=None, blank=True)
created = models.DateField(auto_now=False)
tags = TaggableManager()
slug = models.SlugField(max_length=130, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
favourites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True)
newmanager = NewManager() # custom manager
excerpt = models.TextField(null=True)
objects = models.Manager()
status = models.CharField(max_length=10, choices=options, default='draft')
def __str__(self):
return self.name
def total_likes(self):
return self.likes.count()
def get_absolute_url(self):
# return reverse("forum:topic_detail", kwargs={"slug": self.url})
return reverse_lazy('forum:topic_detail', kwargs={'slug': self.slug})
def tag_list(self) -> str:
return u", ".join(o.name for o in self.tags.all())
class Meta:
verbose_name = 'Topic'
verbose_name_plural = 'Topics'
views.py
def like_topic(request, id):
if request.method == 'POST':
topic = Topic.objects.get(id=id)
if topic.likes.filter(id=request.user.id).exists():
topic.likes.remove(request.user.id)
else:
topic.likes.add(request.user.id)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def favorite_add(request, id):
topic_favorite = get_object_or_404(Topic, id=id)
if topic_favorite.favourites.filter(id=request.user.id).exists():
topic_favorite.favourites.remove(request.user)
else:
topic_favorite.favourites.add(request.user)
return HttpResponseRedirect(request.META['HTTP_REFERER'])
def favouritie_list(request):
new = Topic.newmanager.filter(favourites=request.user.id)
return render(request, 'favourites/favourite.html', {'new': new})
Ошибка возникает в строке "topic.likes.add(request.user.id)".
Traceback Switch to copy-and-paste view
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/db/backends/base/base.py, line 267, in _commit
return self.connection.commit() …
Local vars
The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/core/handlers/exception.py, line 55, in inner
response = get_response(request) …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/core/handlers/base.py, line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
/home/ioann/new_project/new_projects/new_projects/programming_project/forum/views.py, line 265, in like_topic
topic.likes.add(request.user.id) …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py, line 1057, in add
self._add_items( …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/db/transaction.py, line 255, in __exit__
connection.commit() …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/utils/asyncio.py, line 26, in inner
return func(*args, **kwargs) …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/db/backends/base/base.py, line 291, in commit
self._commit() …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/db/backends/base/base.py, line 267, in _commit
return self.connection.commit() …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/db/utils.py, line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value …
Local vars
/home/ioann/.local/share/virtualenvs/new_project-VB4uMZT5/lib/python3.8/site-packages/django/db/backends/base/base.py, line 267, in _commit
return self.connection.commit()