例を挙げましょう。あなたはそれから学び、それに応じて変更を加えるだけです。
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