Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...