2013-03-14 40 views
4

我一直在试图在我的应用程序的每个板子上为我的宠物图片创建一个像按钮,但我无法弄清楚如何创建一个,因为它包含Integer。通常我有一个想法和理解我创建的功能。Django Like Button

当用户点击类似按钮时。类似的按钮将增加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 

有人能帮我创建一个像按钮的基础知识吗?所以我可以理解这个函数的逻辑。

回答

15

我假设很多用户可以喜欢很多图片。

你需要另一种模式:

class Like(models.Model): 
    user = models.ForeignKey(User) 
    picture = models.ForeignKey(Picture) 
    created = models.DateTimeField(auto_now_add=True) 

并调用喜欢像这样的数字:

p = Picture.objects.get(...) 
number_of_likes = p.like_set.all().count() 

为了增加喜欢的数量,您可能使类似的东西在一个观点:

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 

因此,每当有人点击相同的按钮两次,他只计为一。

要了解当前用户已经喜欢所显示的图像或不:

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 

希望这有助于。

+1

这是完美的,如果他想保持喜欢日志。如果没有,我会想''Picture'模型中的一个简单的'number_of_likes'字段。 – 2013-03-14 11:36:35

+1

那么函数每次会增加1? – donkeyboy72 2013-03-14 11:37:45

+1

谢谢你的帮助 – donkeyboy72 2013-03-14 11:51:31

0

我想做类似的事情,并使用“Django-likes”应用程序为我做了工作。

在模型的末尾,把

secretballot.enable_voting_on(Picture) 

然后你就可以在视图中使用的选票。

你可以在这里看到: https://pypi.python.org/pypi/django-likes/0.1

1

我要与大家分享我的喜欢按钮应用体验

首先创建像应用程序和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应用程序,我们将执行save co mmands只需点击一下鼠标对心脏或拇指或任何你想要的,一旦你创建AJAX应用程序,然后不改变任何车型只是adjsut网址,并获得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) # 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) #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_type=post_content_type_by.get_content_type,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模板,我只是这么称呼它。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中,然后从like.html中返回ajax数据,如果数据是新的并且它将大拇指上色为红色,如果数据为假,意味着该数据已经保存但现在你想删除像,所以然后拇指彩色回到正常的颜色,如果数据是真实的,这意味着你已经创建了像这篇文章的数据,但是然后你删除你的拇指,但现在你想再次喜欢拇指去红了起来

好,这是几乎完成,但请记住,当页面刷新所有颜色的大拇指,并计算在页面未显示likers,所以它是如此简单只是写一些小的代码,它会重新加载一切

所以我们在这里所做的,我们创建类似于应用程序,并在数据库的类似表格中创建数据之后,用户创建数据后永远不会被用户删除,只需通过布尔值将其更改为喜欢的真或假状态因此,作为一个admi ñ你总是会保留所有可能对我们有用的数据,但棘手的部分是,所有的事件都是由JavaScript处理的,所以你必须注意用jQuery编写代码时,例如确保Ajax运行良好,而且我也想提及这一点,如果在你的页面例如首先你只加载10个帖子,然后滚动页面和页面自动加载其他10个帖子,像那样的按钮不会工作,因为你的主要jQuery代码在页面不会工作在加载的div,所以我的意思是你必须做一些额外的事情,

但主要的想法,我想分享我的自定义喜欢和ajax应用程序,它为我工作,这一个永远不会失败版本为我:D,真诚