jquery - Need help making Django + Ajax like button -
i new coding , have implemented button online book - tango django:
http://www.tangowithdjango.com/book17/chapters/ajax.html#add-a-like-button
however project need record users have liked , ensure can item once (similar instagram/facebook). have looked @ other related questions online have found there no laid out answer other beginners follow. if easy follow answer me , other people trying achieve same in future, appreciated!
my current code follows:
models
class userproject(models.model): user = models.foreignkey(user) title = models.charfield(max_length=100) date_created = models.datetimefield(auto_now_add=true) project_likes = models.integerfield(default=0) slug = models.slugfield(max_length=100, unique=true)
views
@login_required def like_project(request): proj_id = none if request.method == 'get': proj_id = request.get['project_id'] likes = 0 if proj_id: proj = userproject.objects.get(id=int(proj_id)) if proj: likes = proj.project_likes + 1 proj.project_likes = likes proj.save() return httpresponse(likes)
template
<strong id="like_count">{{ project.project_likes }}</strong> likes {% if user.is_authenticated %} <button id="likes" data-projid="{{project.id}}" class="btn btn-danger-outline btn-sm" type="button"> <i class="fa fa-heart-o" aria-hidden="true"></i> </button> {% endif %}
url
url(r'^like_project/$', views.like_project, name='like_project'),
ajax
$(document).ready(function() { $('#likes').click(function(){ var projid; projid = $(this).attr("data-projid"); $.get('/like_project/', {project_id: projid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); });
if want make sure no user
likes same userproject
twice, can not store number of likes in project_likes
field, should rather create separate model (e.g. userlikes
) foreignkeys
user
, userproject
, , e.g. time @ user liked userproject
. can make function on userproject
model count number of likes.
Comments
Post a Comment