Подтвердить что ты не робот

Моя собственная кнопка Like: Django + Ajax - Как?

Итак, мне не удалось превратить это представление в вызов Ajax:

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

Мне кажется, мне нужны jQuery и JSON, но я не уверен, как реализовать его здесь, чтобы создать свою собственную "понравившуюся кнопку" для моего сайта. Любые мысли/предложения?

4b9b3361

Ответ 1

Я приведу вам пример. Вы просто учитесь на этом и вносите соответствующие изменения.

myapp.models.py (упрощенная модель компании):

from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify


class Company(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    likes = models.ManyToManyField(User, related_name='likes')

    @property
    def total_likes(self):
        """
        Likes for the company
        :return: Integer: Likes for the company
        """
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Company, self).save(*args, **kwargs)

myapp.urls.py (URL-адрес для представления):

url(r'^like/$', 'myapp.views.like', name='like'),

myapp.views.py (просмотр):

from django.http import HttpResponse
try:
    from django.utils import simplejson as json
except ImportError:
    import json
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

from myapp.models import Company


@login_required
@require_POST
def like(request):
    if request.method == 'POST':
        user = request.user
        slug = request.POST.get('slug', None)
        company = get_object_or_404(Company, slug=slug)

        if company.likes.filter(id=user.id).exists():
            # user has already liked this company
            # remove like/user
            company.likes.remove(user)
            message = 'You disliked this'
        else:
            # add a new like for a company
            company.likes.add(user)
            message = 'You liked this'

    ctx = {'likes_count': company.total_likes, 'message': message}
    # use mimetype instead of content_type if django < 5
    return HttpResponse(json.dumps(ctx), content_type='application/json')

Шаблон:

<input type="button" id="like" name="{{ company_slug }}" value="Like" />

<script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'like' %}",
               data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert('Company likes count is now ' + response.likes_count);
                },
                error: function(rs, e) {
                       alert(rs.responseText);
                }
          }); 
    })
</script>

Некоторые инструкции по использованию тега url в шаблоне:

  • Если Django < 1.3 используйте тег url без кавычек вокруг имени URL-адреса, как этот {% url like %}
  • Если Django > 1.3 and < 1.5, то вы должны добавить {% load url from future %} at top level of your template and enclosed your URL name with quotes as I have done in my answer
  • Если Django >= 1.5, то просто удалите {% load url from future %} и вложенное имя URL с кавычками как {% load url from future %} будет помечено как устаревшее и будет удалено в Django 1.9

Ответ 2

Написание этого здесь, так как у меня недостаточно репутации для комментариев, и изменения должны быть не менее 6 символов. В новых версиях Django вам необходимо передать путь к функции просмотра или имя URL-адреса в тег шаблона url в виде строки. Поэтому строка 7 вышеуказанного шаблона будет:

url: "{% url 'like' %}",

Вот часть документация, которая поддерживает это.