So I’ve been having trouble turning this view into an Ajax call:
def company_single(request, slug):
company = get_object_or_404(CompanyProfile, slug=slug)
company_list = CompanyProfile.objects.get(slug=slug)
try:
tcompany = CompanyLikes.objects.get(company=company_list)
total_likes = tcompany.likes
user_liked = CompanyLikes.objects.get(user=request.user)
except:
total_likes = 0
instance, created = CompanyLikes.objects.get_or_create(company=company_list)
likes_form = CompanyLikesForm(request.POST or None, instance=instance)
if likes_form.is_valid():
this = likes_form.save(commit=False)
try:
if user_liked:
this.likes -=1
this.user.remove(request.user)
except:
this.user.add(request.user)
this.likes += 1
this.save()
return render_to_response('company.html', locals(), context_instance=RequestContext(request))
I think I need jQuery and JSON, but I’m not sure how to implement it here to make my own “like button” for my site. Any thoughts/suggestions?
I will give you an example. You just learn from it and make changes accordingly.
myapp.models.py (simplified company model):
myapp.urls.py (URL for a view):
myapp.views.py (View):
The template:
Some instructions for using The url tag in template:
Django < 1.3useurltag without quotes around URL name like this{% url like %}Django > 1.3 and < 1.5then you should add{% load url from future %} at top level of your template and enclosed your URL name with quotes as I have done in my answerDjango >= 1.5then simply remove{% load url from future %}and enclosed URL name with quotes as{% load url from future %}is marked as to be deprecated and will be removed inDjango 1.9