Я пытаюсь заставить пользователя перестать добавлять книги в избранное, когда они уже добавлены, и показать сообщение в шаблоне. Вот мой класс django python:
class User(models.Model):
fname = models.CharField(max_length=255)
lname = models.CharField(max_length=255)
email = models.EmailField()
password = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
class Book(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
uploaded_by = models.ForeignKey(User,
related_name="book_uploaded", on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = BookManager()
class Like(models.Model):
u_like = models.ForeignKey(
User, related_name="user_like", on_delete=models.CASCADE)
b_like = models.ForeignKey(
Book, related_name="book_like", on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
А вот мой views.py
:
def book_info(request, id):
user_who_like = Book.objects.get(id=id).book_like.all()
context = {
'book': Book.objects.get(id=id),
'user': User.objects.get(id=request.session["user_id"]),
'user_who_like': Book.objects.get(id=id).book_like.all(),
'user_uploaded': Book.objects.first().uploaded_by,
}
return render(request, 'book_info.html', context)
def like(request, id):
book = Book.objects.get(id=id)
user = User.objects.get(id=request.session["user_id"])
like = Like.objects.create(u_like=user, b_like=book)
return redirect(f"/books/{book.id}")
Ценю всю вашу помощь! Спасибо