我想用ajax为我的django网站创建一个赞按钮。
我已经创建了一个“赞”按钮,但是该按钮接受单个用户的多次赞。
现在我想创建一个按钮,每个用户可以使用一个按钮。
答案 0 :(得分:0)
您将必须有一个AJAX请求,该请求发送喜欢的项目,然后在视图中进行处理。
models.py
class Movie(models.Model):
name = models.CharField(max_length=55, blank=False)
def __str__:
return self.name
class MovieLike(models.Model):
movie = models.ForeignKey(Movie, blank=False, null=False)
user = models.ForeignKey(User, blank=False, null=False)
class Meta:
unique_together = ('movie', 'user',)
def __str__:
return self.movie.name
views.py
class LikeView(View):
def post(self, request, *args, **kwargs):
user = request.user
movie_id = request.POST['movie_id']
movie = Movie.objects.get(id=movie_id)
user_liked, created = MovieLike.objects.get_or_create(movie=movie, user=user)
return JsonResponse({"created": created})
urls.py
urlpatterns = [
...
path('movie/like/', views.LikeView.as_view(), name='movie_like'),
...
]
html
<a href="#" class="js-likeMovie" data-movie-id="{{ movie.id }}">
Like Movie
</a>
jQuery AJAX
document.querySelectorAll('.js-likeMovie').addEventListener('click', function (e) {
e.preventDefault()
var movie_id = this.getAttribute('data-movie-id');
$.ajax({
type: "POST",
url: "{url 'movie_like'}",
data: {csrfmiddlewaretoken: "{{ csrf_token }}", movie_id: movie_id}
})
.done(function (response) {
console.log(response)
})
})