0
I’m trying to create a favorite button for an app’s posts, but I can’t figure out how to create one because it contains an entire number. When the user clicks on the favorite button. The button will increase to 1 and will be displayed near the image.
This is my Post model.
class Post(models.Model):
title = models.CharField(max_length=100)
slug = AutoSlugField(unique=True, always_update=False, populate_from="title")
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField(max_length=1050)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
image = models.ImageField(null=True, blank=True, upload_to=upload_perfil_user)
category = models.ForeignKey(
Category, related_name="posts", on_delete=models.CASCADE, null=True
)
class Meta:
ordering = ("-created",)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("blog:detail", kwargs={"slug": self.slug})
def comment_number(self):
return len(self.comment_set.all())
E esse é o modelo do Favorite :
class Favorite(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
But I’m having extreme difficulty creating the system view :
class Favorite(CreateView):
model = Favorite
def form_valid(self):
form.instance.author=request.user #id do usuario
#id do post
#se o usuario ja favoritou, então não faça nada
#se o usuario não favoriou então suba a info pro banco (id_user, id_post)
#retorne o mesmo url talvez... Não tive ideia pro retorno da função
Can anyone help me create the view from the favorite button ? I have the table in the bank due to the model, but wanted to understand the logic of how to create the view in a way that the two foreing Keys (User and Post) are populated, with the exception of Foreign key user is one Too Many Post