|
4 | 4 |
|
5 | 5 | from django.conf import settings |
6 | 6 | from django.core.paginator import Paginator |
7 | | -from django.http import HttpResponse, HttpResponseForbidden |
8 | | -from django.shortcuts import get_object_or_404 |
9 | | -from django.shortcuts import render |
| 7 | +from django.http import HttpResponse, HttpResponseForbidden, JsonResponse |
| 8 | +from django.shortcuts import get_object_or_404, render |
10 | 9 | from django.templatetags.static import static |
11 | 10 | from django.utils import timezone |
12 | 11 | from django.utils.translation import gettext_lazy as _ |
13 | 12 | from django.views.decorators.csrf import csrf_exempt |
14 | 13 | from django.views.generic.detail import DetailView |
15 | 14 | from django.views.generic.list import ListView |
16 | 15 | from haystack.views import SearchView |
| 16 | +from django.contrib.auth.decorators import login_required |
17 | 17 |
|
18 | | -from blog.models import Article, Category, LinkShowType, Links, Tag |
| 18 | +from blog.models import Article, Category, LinkShowType, Links, Tag, Favorite |
19 | 19 | from comments.forms import CommentForm |
20 | 20 | from djangoblog.utils import cache, get_blog_setting, get_sha256 |
21 | 21 |
|
@@ -373,3 +373,46 @@ def permission_denied_view( |
373 | 373 | def clean_cache_view(request): |
374 | 374 | cache.clear() |
375 | 375 | return HttpResponse('ok') |
| 376 | + |
| 377 | + |
| 378 | +@login_required |
| 379 | +def add_favorite(request, article_id): |
| 380 | + article = get_object_or_404(Article, id=article_id) |
| 381 | + favorite, created = Favorite.objects.get_or_create( |
| 382 | + user=request.user, |
| 383 | + article=article |
| 384 | + ) |
| 385 | + return JsonResponse({ |
| 386 | + 'status': 'success', |
| 387 | + 'message': '收藏成功' if created else '已经收藏过了' |
| 388 | + }) |
| 389 | + |
| 390 | +@login_required |
| 391 | +def remove_favorite(request, article_id): |
| 392 | + article = get_object_or_404(Article, id=article_id) |
| 393 | + Favorite.objects.filter( |
| 394 | + user=request.user, |
| 395 | + article=article |
| 396 | + ).delete() |
| 397 | + return JsonResponse({ |
| 398 | + 'status': 'success', |
| 399 | + 'message': '取消收藏成功' |
| 400 | + }) |
| 401 | + |
| 402 | +@login_required |
| 403 | +def favorite_list(request): |
| 404 | + favorites = Favorite.objects.filter(user=request.user).select_related('article') |
| 405 | + return render(request, 'blog/favorite_list.html', { |
| 406 | + 'favorites': favorites |
| 407 | + }) |
| 408 | + |
| 409 | +@login_required |
| 410 | +def check_favorite(request, article_id): |
| 411 | + article = get_object_or_404(Article, id=article_id) |
| 412 | + is_favorite = Favorite.objects.filter( |
| 413 | + user=request.user, |
| 414 | + article=article |
| 415 | + ).exists() |
| 416 | + return JsonResponse({ |
| 417 | + 'is_favorite': is_favorite |
| 418 | + }) |
0 commit comments