Django like button

I’m trying to create a button for my pets in each board for my application, but I can’t figure out how to create it, because it contains Integer. I usually have an idea and understanding of the functions I create.

When the user clicks a similar button. A similar button will increase by 1 and it will be displayed next to the image.

This is my image module.

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 

Can anyone help me create the basics of a similar button? Therefore, I can understand the logic of the function.

+4
source share
3 answers

I assume that many users may like a lot of photos.

You will need another model:

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

And name the amount you like like this:

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

To increase the number of people you like, perhaps something like this in the view:

 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 

therefore, whenever someone presses the same button twice, he counts only one.

To find out if the current user likes the displayed image or not:

 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 

Hope this helps.

+17
source

I will share with you my experience in using the Like button.

first create a like application and create a like model

 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) 

then you should have an ajax application that we will execute, saving commands with just one click of the mouse on the heart or thumb or whatever you want. Once you create the ajax application, don’t change anything in the models, just assign the URLs and go to ajax.views and set the codes

 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}) 

and right after that we will create our ajax templates to return and save ajax data, I just call it as .html

  {% if okey == 'new' %} new {% elif okey == 'false' %} false {% elif okey == 'true' %} true {% endif %} 

Now create an HTML index or where you want to set as buttons and write jquery codes

  $('.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'); } } }); 

above the example, when we click the thumb and it saves the data in LikeModel, then from like.html, which returns ajax data if the data is new and they turn the thumb red if the data is false, which means that this data is already saved but now you want to delete how, so then the thumb returned to normal color, and if the data is true, which means that you already created as data for this post, but then you delete the thumb, but now you want to like it again and not the thumb goes red again

Well, it's almost done, but remember that when the page refreshes all the colored icons and calculated values ​​not shown on the page, so it's so simple, just write a few small codes and everything will load again

So, what we did here, we created as applications and inside a similar table in the database, after the data is created by the user, they will never be deleted by the user, they simply change to the true or false state they like using a logical field, so as an administrator you will always store all the data that may be useful to us, but the difficult part is that all events are processed by javascript, so you should be careful when writing codes using jquery, for example, convince ajax works well, and I want to mention this too, if, for example, on your page you first load only 10 posts, and then scrolling the page and the page automatically loads the remaining 10 posts, etc., then these buttons do not will work because your main jquery codes on the page will not work in the loaded div, so I mean that you have to do some additional things for this,

But the main idea that I wanted to share my custom applications like likes and ajax, it worked for me, and this version never failed for me: D, sincerely

+2
source

I wanted to do a similar thing, and using the django-likes app did the job for me.

At the end of your model, put

 secretballot.enable_voting_on(Picture) 

And then you can use voices in the view.

You can see it here: https://pypi.python.org/pypi/django-likes/0.1

0
source

Source: https://habr.com/ru/post/1469207/


All Articles