12

所以我一直无法将此视图转换为 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,但我不确定如何在这里实现它来为我的网站制作我自己的“点赞按钮”。有什么想法/建议吗?

4

2 回答 2

24

我会给你一个例子。您只需从中学习并做出相应的更改。

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标签的一些说明:

  • 如果像这样在 URL 名称周围Django < 1.3使用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
于 2012-12-22T23:45:52.520 回答
7

在这里写这篇文章是因为我没有足够的声誉来发表评论,并且编辑必须至少有 6 个字符。在新版本的 Django 中,您需要将视图函数的路径或 url 的名称作为字符串传递给 url 模板标签。因此上述模板的第 7 行将是:

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

这是支持这一点的文档的一部分。

于 2014-06-13T10:36:00.180 回答