Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

django: how to implement public like button

I would like to implement a simple 'like' button. No need for user authentication etc, I prefer to be simple, on click +1 like. Any ideas on how to implement this like btn? I appreciate your help!

models.py

class Mainnews(models.Model):
    author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True)
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(upload_to = 'photos/%Y/%m/%d/')
    is_published = models.BooleanField(default = True)
    publish_date = models.DateTimeField(default = datetime.now, blank = True)
    views_counter = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    
    def number_of_likes(self):
        return self.likes.count()
        
    def __str__(self):
        return self.title
question from:https://stackoverflow.com/questions/65877625/django-how-to-implement-public-like-button

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a view with an argument for the Mainnews objects primary key (you can do it in URL like this /main-news/1/like or you can post it in request.POST)

Then in your like view (create a view that does not need authentication) get the object from the database and do this: main_news.likes = main_news.likes + 1

your view must be POST because you want to change the db.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...