Django Twitter clone. How to restrict user from liking a tweet more than once?
<p>I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.</p>

<p>models.py</p>

<pre><code>class Howl(models.Model):
    author = models.ForeignKey(User, null=True)
    content = models.CharField(max_length=150)
    published_date = models.DateTimeField(default=timezone.now)
    like_count = models.IntegerField(default=0)
    rehowl_count = models.IntegerField(default=0)

    def get_absolute_url(self):
        return reverse('howl:index')

    def __str__(self):
        return self.content 
</code></pre>

<p>views.py</p>

<pre><code>class HowlLike(UpdateView):
    model = Howl
    fields = []

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.like_count += 1
        instance.save()

        return redirect('howl:index')
</code></pre>

<p>Django Twitter clone. How to restrict user from liking a tweet more than once?</p>

<p>As well as tracking how many <code>Likes</code> a post has, you'll probably also want to track who has "Liked" each post.  You can solve both of these problems by creating a joining table <code>Likes</code> with a unique key on <code>User</code> and <code>Howl</code>.</p>

<p>The unique key will prevent any <code>User</code> from doing duplicate likes.</p>

<p>You can do this in Django with a <a href="https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/" rel="nofollow"><code>ManyToManyField</code></a>, note that since this means adding a second <code>User</code> relationship to <code>Howl</code>, we need to disambiguate the relationship by providing a <code>related_name</code></p>

<p>Eg:</p>

<pre><code>class Howl(models.Model):
    author = models.ForeignKey(User, null=True, related_name='howls_authored')
    liked_by = models.ManyToManyField(User, through='Like')

    # ...rest of class as above


class Like(models.Model):
    user = models.ForeignKey(User)
    howl = models.ForeignKey(Howl)

    class Meta:
      unique_together = (('user', 'howl'))
</code></pre>

<p><code>like_count</code> count then becomes redundant, since you can use <code>Howl.liked_by.count()</code> instead.</p>

<p>The other benefit of this is that it allows you to store information about the <code>Like</code> - eg when it was added.</p>

python django