我一直在尝试为我的应用程序在每个主板上为我的宠物图片创建一个类似的按钮,但我无法弄清楚如何创建一个因为它包含整数.通常我对我创建的功能有一个想法和理解.
当用户点击"赞"按钮时.相似按钮将增加1,它将显示在图片附近.
这是我的图片模块.
class Picture(models.Model):
user = models.ForeignKey(User)
board = models.ForeignKey(Board ,related_name='lo')
image = models.FileField(upload_to="images/",blank=True,null=True)
description = models.TextField()
is_primary = models.BooleanField(default=False)
def __unicode__(self):
return self.description
Run Code Online (Sandbox Code Playgroud)
有人可以帮我创建一个类似按钮的基础知识吗?所以我可以理解函数的逻辑.
maw*_*awi 25
我假设很多用户可以喜欢很多图片.
你需要另一个模型:
class Like(models.Model):
user = models.ForeignKey(User)
picture = models.ForeignKey(Picture)
created = models.DateTimeField(auto_now_add=True)
Run Code Online (Sandbox Code Playgroud)
并拨打喜欢这样的人数:
p = Picture.objects.get(...)
number_of_likes = p.like_set.all().count()
Run Code Online (Sandbox Code Playgroud)
为了增加喜欢的数量,你可能会在视图中出现类似的情况:
def like(request, picture_id):
new_like, created = Like.objects.get_or_create(user=request.user, picture_id=picture_id)
if not created:
# the user already liked this picture before
else:
# oll korrekt
Run Code Online (Sandbox Code Playgroud)
因此,每当有人点击两次相同的按钮时,他只算作一个.
要确定当前用户是否已经喜欢所显示的图像:
def picture_detail(request, id):
pic = get_object_or_404(Picture, pk=id)
user_likes_this = pic.like_set.filter(user=request.user) and True or False
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
我会和你分享我喜欢按钮的应用程序体验
首先创建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)
Run Code Online (Sandbox Code Playgroud)
那么你应该有 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})
Run Code Online (Sandbox Code Playgroud)
在那之后我们将创建我们的ajax模板来返回和保存ajax数据,我把它叫做like.html
{% if okey == 'new' %}
new
{% elif okey == 'false' %}
false
{% elif okey == 'true' %}
true
{% endif %}
Run Code Online (Sandbox Code Playgroud)
现在创建您的索引 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');
}
}
});
Run Code Online (Sandbox Code Playgroud)
在示例上方,当我们单击拇指并将数据保存在 LikeModel 中,然后从返回 ajax 数据的 like.html 中,如果数据是新的并且将拇指着色为红色,如果数据为假,则表示该数据已经保存但现在你想删除喜欢,然后拇指颜色恢复正常颜色,如果数据是真的,这意味着你已经为这篇文章创建了喜欢的数据,但你删除了你的拇指,但现在你想再次喜欢,而不是拇指去又红了
好的,这几乎完成了,但请记住,当页面刷新页面中未显示的所有彩色拇指和计数的喜欢者时,因此非常简单,只需编写一些小代码,它就会再次加载所有内容
所以我们在这里所做的,我们在数据库中创建了类似应用程序和类似表,在用户创建数据之后,它永远不会被用户删除,它只是通过布尔字段更改为喜欢的真或假状态,所以作为管理员,您总是会保留所有可能对我们有用的数据,但棘手的部分是,所有事件都由 javascript 处理,因此您在使用 jquery 编写代码时必须注意,例如确保 ajax 运行良好,我也想提到这一点,例如,如果在您的页面中,您首先只加载 10 个帖子,然后滚动页面和页面会自动加载其他 10 个帖子,然后像这样的按钮不起作用,因为您的主要 jquery 代码在页面中无法在加载的 div 中工作,所以我的意思是你必须为此做一些额外的事情,
但是我想分享我的自定义喜欢和 ajax 应用程序的主要想法,它对我有用,这个版本对我来说永远不会失败:D,真诚的
| 归档时间: |
|
| 查看次数: |
13173 次 |
| 最近记录: |