我将与您分享我的喜欢按钮应用程序体验
首先创建like app和like.models里面建立
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class LikeModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
liked = models.BooleanField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
timestamp = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.user.username)
那么你应该有 ajax 应用程序,我们将执行保存命令,只需单击心脏或拇指或任何你想要的,一旦你创建了 ajax 应用程序,然后不要更改模型中的任何内容,只需调整 url 并进入 ajax.views 并建立代码
def like_it(request):
user = request.user
if request.method == 'POST':
ObjectId = int(request.POST['objectid'])
Tip = str(request.POST['contentType'])
likes = LikeModel.objects.filter(object_id=ObjectId, content_object=Tip) # in here we filtered the particular post with its id
if likes: # if the particular post is there
if str(user) in str(likes): # then we check the user which is us, in there
like_obj = LikeModel.objects.get(user=user,object_id=ObjectId, content_object=Tip) #if we there and we returned this data, this part for saving data, I mean if this data is already created than we dont have to delete and create again, we just change LikeModel.liked true or false state, so that if you create like and it will never delete, it just change liked or like state
else:
pass
if Tip == 'UserPost':
post_content_type_by = UserPost.objects.all().first()
if str(user) not in str(likes):
like = LikeModel.objects.create(user=user, liked=True, content_object=ContentType.objects.get_for_model(Tip), object_id=ObjectId)
like.save() # if data is created then we say 'new'
okey = 'new'
elif str(user) in str(likes) and like_obj.liked:
like_obj.liked = False
like_obj.save() # if data is already there, then we save it False
okey = 'false'
elif str(user) in str(likes) and like_obj.liked == False:
like_obj.liked = True
like_obj.save() # if data is already changed to False and we save again to True
okey = 'true'
return render(request,'ajaxlike.html',{'likes':likes,'okey':okey})
之后我们将创建用于返回和保存 ajax 数据的 ajax 模板,我将其命名为 like.html
{% if okey == 'new' %}
new
{% elif okey == 'false' %}
false
{% elif okey == 'true' %}
true
{% endif %}
现在创建您的索引 html 或您想要建立类似按钮的任何位置,并编写 jquery 代码
$('.thumb').click(function(){
var indx = $('.thumb').index(this)
var ObjectId = $('.ObjectId:eq('+indx+')').text()
$.ajax({
type: 'POST',
url: '/ajax/ajaxlike/',
data: {
'contentType':'UserPost',
'objectid':ObjectId,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
},
success: LikePost,
dataType: 'html'
});
function LikePost(data, textStatus, jqXHR){
if($.trim(data) == 'new'){
$('.thumb:eq('+indx+')').css('color','#FF0033');
}else if($.trim(data) == 'false'){
$('.thumb:eq('+indx+')').css('color','');
}else if($.trim(data) == 'true'){
$('.thumb:eq('+indx+')').css('color','#FF0033');
}
}
});
在上面的示例中,当我们单击拇指并将数据保存在 LikeModel 中,然后从返回 ajax 数据的 like.html 中保存数据,如果数据是新的并且将拇指着色为红色,如果数据为 false,则表示该数据已经保存但是现在你想删除喜欢,所以然后拇指颜色恢复正常颜色,如果数据是真的,这意味着你已经为这篇文章创建了类似的数据,但是你删除了你的拇指,但现在你想再次喜欢所以拇指去又红了
好的,这几乎完成了,但请记住,当页面刷新所有彩色拇指并计算页面中未显示的点赞数时,它是如此简单,只需编写一些小代码,它就会再次加载所有内容
所以我们在这里所做的,我们创建了类似的应用程序并在数据库的类似表中,在用户创建数据之后,它将永远不会被用户删除,它只是通过布尔字段更改为喜欢的真假状态,所以作为管理员,您始终会保留所有可能对我们有用的数据,但棘手的部分是,所有事件都由 javascript 处理,因此您在使用 jquery 编写代码时必须注意,例如确保 ajax 运行良好,我也想提一下这一点,例如,如果在您的页面中首先加载 10 个帖子,然后滚动页面和页面会自动加载其他 10 个帖子,然后喜欢按钮将不起作用,因为您的主要 jquery 代码在页面中无法在加载的 div 中工作,所以我的意思是你必须为此做一些额外的事情,
但是我想分享我的自定义like和ajax应用程序的主要想法,它对我有用,这个对我来说从来没有失败过:D,真诚的