我已经创建了一个“喜欢”按钮,但这不是我想要的,我当前喜欢的按钮可以被用户喜欢的次数多次。
enter code here
##models.py
class Images(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='images_created', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, null=True,
blank=True)
message_likes = models.IntegerField(default=0)
objects = InheritanceManager()
##views.py
def like_treasure(request):
treasure_id = request.POST.get('treasure_id', None)
message_likes = 0
if (treasure_id):
treasure = Postsms.objects.get(id=int(treasure_id))
if treasure is not None:
message_likes = treasure.message_likes + 1
treasure.message_likes = message_likes
treasure.save()
return HttpResponse(message_likes)
## $
$('button').on('click', function(event){
event.preventDefault();
var element = $(this);
$.ajax({
url : '/like_treasure/',
type : 'POST',
data : { treasure_id : element.attr("data-id")},
success : function(response){
element.html(' ' + response);
}
});
});
##html
<button style="background-color: red" id ="likes" data-id="{{foo.id}}"
class="btn btn-mini glyphicon glyphicon-heart"
type="button" >
{% if foo.message_likes > 0 %} {{ foo.message_likes }} {% endif %}
答案 0 :(得分:0)
在图像模型中采用布尔字段而不是IntegerField。因此,用户只能喜欢一次图像。休息一下,用布尔字段在前端处理它。