views.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. from django.shortcuts import render, redirect
  2. from django.http import HttpResponse, JsonResponse
  3. from django.contrib.auth.models import User
  4. from django.contrib.auth.decorators import login_required
  5. from django.core.paginator import Paginator
  6. from django.core import serializers
  7. from django.db.models import Q
  8. import json
  9. import markdown
  10. from .models import ArticlePost, ArticleColumn
  11. from .form import ArticlePostForm
  12. from comment.models import Comment
  13. from comment.forms import CommentPost
  14. # 视图函数
  15. def home(request):
  16. articles = ArticlePost.objects.all()[0:][:20]
  17. context = {'articles': articles}
  18. return render(request, 'article/home.html', context)
  19. def article_list(request):
  20. search = request.GET.get('search')
  21. order = request.GET.get('order')
  22. tag = request.GET.get('tag')
  23. column = request.GET.get('column')
  24. articles = ArticlePost.objects.all()
  25. articles, search = get_articles_ordered(articles, order, search, column, tag)
  26. # 分页,暂时关闭
  27. # paginator = Paginator(article_list, 4)
  28. # page = request.GET.get('page')
  29. articles = articles[0:][:10]
  30. context = {'articles': articles, 'order': order, 'search': search, 'column': column, 'tag': tag, }
  31. return render(request, 'article/articles.html', context)
  32. def get_articles_ordered(articles, order, search, column, tag):
  33. # 搜索查询集
  34. if search and search != 'None':
  35. articles = articles.filter(
  36. Q(title__icontains=search) |
  37. Q(body__icontains=search)
  38. )
  39. else:
  40. search = ''
  41. # 分类查询集
  42. if column is not None and column.isdigit():
  43. articles = articles.filter(column=column)
  44. # 标签查询集
  45. if tag and tag != 'None':
  46. articles = articles.filter(tags__name__in=[tag])
  47. # 排序
  48. if order == 'total_views':
  49. articles = articles.order_by('-total_views')
  50. return articles, search
  51. def callajax(request):
  52. if request.method == 'POST':
  53. response_json = request.POST
  54. response_json = json.dumps(response_json)
  55. data = json.loads(response_json)
  56. counter = int(data['counter'])
  57. articles = ArticlePost.objects.all()
  58. if 'articles' in data['flag']:
  59. search = data['search']
  60. column = data['column']
  61. tag = data['tag']
  62. order = data['order']
  63. articles, search = get_articles_ordered(articles, order, search, column, tag)
  64. articles = articles[counter:][:10]
  65. if articles:
  66. context = {'articles': articles}
  67. if 'articles' in data['flag']:
  68. return render(request, 'article/order_call.html', context)
  69. else:
  70. return render(request, 'article/home_call.html', context)
  71. else:
  72. return HttpResponse('已经到底了')
  73. else:
  74. return HttpResponse('What?')
  75. def article_detail(request, id):
  76. articles = ArticlePost.objects.get(id=id)
  77. comments = Comment.objects.filter(article=id)
  78. articles.total_views += 1
  79. articles.save(update_fields=['total_views'])
  80. md = markdown.Markdown(
  81. extensions=[
  82. 'markdown.extensions.extra',
  83. 'markdown.extensions.codehilite',
  84. 'markdown.extensions.toc'
  85. ])
  86. articles.body = md.convert(articles.body)
  87. comment_form = CommentPost()
  88. toc_flag = True
  89. if 'li' not in md.toc:
  90. toc_flag = False
  91. context = {'article': articles, 'toc': md.toc, 'comments': comments, 'comment_form': comment_form,
  92. 'toc_flag': toc_flag}
  93. return render(request, 'article/detail.html', context)
  94. @login_required(login_url='/user/login/')
  95. def article_create(request):
  96. if request.method == 'POST':
  97. article_post_form = ArticlePostForm(request.POST, request.FILES)
  98. # 判断提交的数据是否满足模型要求
  99. if article_post_form.is_valid():
  100. # 保存数据,但是暂时不提交到数据库中
  101. new_article = article_post_form.save(commit=False)
  102. new_article.author = User.objects.get(id=request.user.id)
  103. if request.POST['column'] != 'none':
  104. new_article.column = ArticleColumn.objects.get(id=request.POST['column'])
  105. # 将新文章保存到数据库中
  106. new_article.save()
  107. article_post_form.save_m2m()
  108. return redirect("article:article_list")
  109. # 如果数据不合法,返回错误信息
  110. else:
  111. return HttpResponse("表单有错误,请重新填写")
  112. # 如果用户请求获取数据
  113. else:
  114. # 创建表单类实例
  115. article_post_form = ArticlePostForm()
  116. columns = ArticleColumn.objects.all()
  117. context = {'article_post_form': article_post_form, 'columns': columns}
  118. # 返回模板
  119. return render(request, 'article/create.html', context)
  120. def article_delete(request, id):
  121. article = ArticlePost.objects.get(id=id)
  122. article.delete()
  123. return redirect("article:article_list")
  124. @login_required(login_url='/user/login/')
  125. def article_safe_delete(request, id):
  126. if request.method == 'POST':
  127. article = ArticlePost.objects.get(id=id)
  128. if article.author == User.objects.get(id=request.user.id):
  129. article.delete()
  130. return redirect("article:article_list")
  131. else:
  132. return HttpResponse("你无权限进行此操作")
  133. else:
  134. return HttpResponse("仅允许POST请求")
  135. @login_required(login_url='/user/login/')
  136. def article_update(request, id):
  137. article = ArticlePost.objects.get(id=id)
  138. if article.author == User.objects.get(id=request.user.id):
  139. if request.method == 'POST':
  140. article_post_form = ArticlePostForm(data=request.POST)
  141. if article_post_form.is_valid():
  142. article.title = request.POST['title']
  143. article.body = request.POST['body']
  144. if request.POST['column'] != 'none':
  145. article.column = ArticleColumn.objects.get(id=request.POST['column'])
  146. else:
  147. article.column = None
  148. if request.FILES.get('avatar'):
  149. article.avatar = request.FILES.get('avatar')
  150. article.tags.set(*request.POST.get('tags').split(','), clear=True)
  151. article.save()
  152. return redirect("article:article_detail", id=id)
  153. else:
  154. return HttpResponse("表单内容有误,请重新填写")
  155. else:
  156. article_post_form = ArticlePostForm()
  157. columns = ArticleColumn.objects.all()
  158. context = {'article': article, 'article_post_form': article_post_form, 'columns': columns,
  159. 'tags': ','.join([x for x in article.tags.names()])}
  160. return render(request, 'article/update.html', context)
  161. else:
  162. return HttpResponse("你无权进行此操作")