def add_comment(request, article_id): if request.user.is_authenticated(): a = Article.objects.get(id=article_id) if request.POST and request.POST.get("content", "").strip() != '': form = CommentForm(request.POST) if form.is_valid(): c = form.save(commit=False) c.creation_date = timezone.now() c.article = a c.author = request.user c.save() return HttpResponseRedirect('/articles/get/%s' % article_id) else: form = CommentForm() args = {} args.update(csrf(request)) args['article'] = a args['form'] = form return render_to_response('add_comment.html', args) else: return HttpResponseRedirect('/accounts/login')
def article_detail(request, id, slug): article = get_object_or_404(ArticlePost, id=id, slug=slug) total_views = r.incr("article:{}:views".format(article.id)) r.zincrby('article_ranking', article.id, 1) article_ranking = r.zrange('article_ranking', 0, -1, desc=True)[:10] article_ranking_ids = [int(id) for id in article_ranking] most_viewed = list(ArticlePost.objects.filter(id__in=article_ranking_ids)) most_viewed.sort(key=lambda x: article_ranking_ids.index(x.id)) if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article new_comment.save() else: comment_form = CommentForm() article_tags_ids = article.article_tag.values_list("id", flat=True) similar_articles = ArticlePost.objects.filter( article_tag__in=article_tags_ids).exclude(id=article.id) similar_articles = similar_articles.annotate( same_tags=Count("article_tag")).order_by('-same_tags', '-created')[:4] return render( request, "article/list/article_detail.html", { "article": article, "total_views": total_views, "most_viewed": most_viewed, "comment_form": comment_form, "similar_articles": similar_articles })
def article_detail(request, id, slug): article = get_object_or_404(ArticlePost, id=id, slug=slug) total_views = r.incr("article:{}:views".format(article.id)) if request.method == "POST": if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article new_comment.commentator = request.user new_comment.save() else: return HttpResponseRedirect("/account/login/") else: comment_form = CommentForm() article_tags_ids = article.article_tag.values_list("id", flat=True) similar_articles = ArticlePost.objects.filter( article_tag__in=article_tags_ids).exclude(id=article.id) similar_articles = similar_articles.annotate( same_tags=Count("article_tag")).order_by('-same_tags', '-created')[:4] return render( request, "article/list/article_detail.html", { "article": article, "total_views": total_views, "comment_form": comment_form, "similar_articles": similar_articles })
def list_article_detail(request, article_id, slug): article = get_object_or_404(ArticlePost, id=article_id, slug=slug) total_views = redis_db.incr('article:{}:views'.format(article_id)) redis_db.zincrby('article_ranking', article_id, 1) article_ranking = redis_db.zrange('article_ranking', 0, -1, desc=True)[:10] article_ranking_ids = [ int(article_ranking_id) for article_ranking_id in article_ranking ] most_viewed = list(ArticlePost.objects.filter(id__in=article_ranking_ids)) most_viewed.sort(key=lambda x: article_ranking_ids.index(x.id)) # 推荐相似文章 article_tags_ids = article.article_tag.values_list('id', flat=True) similar_articles = ArticlePost.objects.filter( article_tag__in=article_tags_ids).exclude(id=article.id) similar_articles = similar_articles.annotate( same_tags=Count('article_tag')).order_by('-same_tags', '-create_time') if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article new_comment.save() else: comment_form = CommentForm() return render( request, 'article/list/article_detail.html', { 'article': article, 'total_views': total_views, 'most_viewed': most_viewed, 'comment_form': comment_form, 'similar_articles': similar_articles, })
def detail(request, id): post = Article.objects.get(id=id) all_comment = Comment.objects.filter(article__id=id) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, 'detail.html', {'post': post, 'all_comment': all_comment, 'comment_form': comment_form})
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'comment_form.html', {'form': form})
def edit_comment(request, pk): user = request.user comment = get_object_or_404(Commentary, pk=pk) form = CommentForm(instance=comment) if request.method == 'POST' and user == comment.nick.user: form = CommentForm(request.POST, instance=comment) if form.is_valid(): form.save() return redirect('index') return render(request, 'article/edit_comment.html', { 'form': form, 'user': user, 'comment': comment })
def article_detail(request, id, slug): article = get_object_or_404(ArticlePost, id=id, slug=slug) # total_views = r.incr("article:{}:views".format(article.id)) # import redis # from django.conf import settings # 注:用redis统计文章访问量较快,大型网站常用。此处个人博客不用,省的每次开redis服务器 # r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) # r.zincrby('article_ranking', 1, article.id) # 每次访问时,自增article_ranking里对应article_id的分数 # 按照索引范围获取name对应的有序集合的元素,0~-1表示从开头到结尾,排序规则desc=True表示从大到小 # article_ranking = r.zrange("article_ranking", 0, -1, desc=True)[:10] # article_ranking_ids = [int(id) for id in article_ranking] # 对字典而言,直接for的话取的是key # most_viewed = list(ArticlePost.objects.filter(id__in=article_ranking_ids)) # id__in可以传进列表一次取值 # most_viewed.sort(key=lambda x: article_ranking_ids.index(x.id)) # 用id排序 if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article new_comment.save() else: comment_form = CommentForm() # get方法的话,直接创建表单返回 article.views += 1 article.save(update_fields=['views']) # 存进数据库 most_viewed_articles = ArticlePost.objects.all().order_by( '-views')[:4] # 以views数量降序排序 article_tags_ids = article.article_tag.values_list( "id", flat=True) # 得到当前对象(article_tag是一个对象)的指定字段值 # exclude排除id相同的文章 similar_articles = ArticlePost.objects.filter( article_tag__in=article_tags_ids).exclude(id=article.id) # 聚合,取4篇相似文章,依照最新和相同标签两种排序方式 similar_articles = similar_articles.annotate( same_tags=Count("article_tag")).order_by('-same_tags', '-created')[:4] # return render(request, "article/list/article_content.html", # {"article": article, "total_views": total_views, # "most_viewed": most_viewed, "comment_form": comment_form, "similar_articles": similar_articles}) return render( request, "article/list/article_content.html", { "article": article, "total_views": article.views, "most_viewed_articles": most_viewed_articles, "comment_form": comment_form, "similar_articles": similar_articles })
def post(self, request, post_pk): try: post = ArticleModels.objects.filter(pk=post_pk, is_delete=False ) except ArticleModels.DoesNotExist: return redirect('article:home') # 接收参数 data = request.POST form = CommentForm(data) # 接收用户的id user_id = request.session.get("id") # 验证数据的合法性 if form.is_valid(): # 获取清洗后的数据 cleaned = form.cleaned_data # 取出清洗后的评论 text = cleaned.get('text') # 保存到数据库 Comment.objects.create(text=text, post_id=post_pk, users_id=user_id) artic = ArticleModels.objects.get(pk=post_pk) myartic = ArticleModels.objects.filter(author=artic.author_id) comment_list = Comment.objects.filter(post_id=post_pk, is_delete=False) context = {'artic': artic, 'myartic': myartic, 'comment_list': comment_list} return render(request, 'article/details.html', context=context) else: artic = ArticleModels.objects.get(pk=post_pk) myartic = ArticleModels.objects.filter(author=artic.author_id) comment_list = Comment.objects.filter(post_id=post_pk, is_delete=False) context = {'artic': artic, 'myartic': myartic, 'form': form, 'comment_list': comment_list} return render(request, 'article/details.html', context=context)
def post_detail(request, post_id): pk = post_id # try: # post = Post.objects.get(id=pk) # except Post.DoesNotExist: # raise Http404('bulunamadı') post = get_object_or_404(Post, id=pk, draft=False) comments = post.comments.all() form = CommentForm(request.POST or None) context = { 'post': post, 'comments': comments, 'form': form } if request.method == 'POST': if form.is_valid(): form.instance.post = post form.save() messages.add_message(request, messages.SUCCESS, 'Basari ile kayit edildi') return redirect('post_detail', post_id=post.id) # if request.method == 'POST': # if form.is_valid(): # form.instance.post = post # form.save() # messages.add_message(request, messages.SUCCESS, # 'Basarıyla olusturuldu') # return render(request, 'article/post_detail.html', context)
def user_comment(request, article_id): """ 用户评论文章的处理函数 :param request: :param article_id: :return: """ user = request.session.get('user') print(user) try: article = Article.objects.get(id=article_id) except Exception: return JsonResponse({'code': 'no', 'msg': '文章不存在!'}) else: comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.article_id = article_id comment.user = user comment.create_time = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) comment.save() article_comment_count = article.comment_set.count() data = create_comment_element(request, user, comment, article_comment_count) return JsonResponse({'code': 'ok', 'data': data}) else: return JsonResponse({'code': 'no', 'msg': '数据格式错误!'})
def article(request, slug): if request.method == "POST": comment_form = CommentForm(data=request.POST) user = comment_form.save().author if comment_form.is_valid() and user.is_authenticated(): Article.objects.get(slug=slug).comments.add(comment_form.save()) else: return HttpResponse("You are not allowed to comment") else: comment_form = CommentForm() return render(request, 'article.html', {'article':Article.objects.get(slug=slug),'comment':comment_form, 'request':request })
def create_comment(request): article_id = int(request.POST['article_id']) article = Article.normal_objects.get(id=article_id) to_comment_id = int(request.POST.get("to_comment_id", 0)) form = CommentForm(request.POST) if to_comment_id != 0: to_comment = Comment.objects.get(id=to_comment_id) new_msg = UserMessage(owner=to_comment.owner, content="有人回复了你的评论'%s' " % to_comment.content[:30], link="/article/articledetail/%s" % article_id, status=0) new_msg.save() else: to_comment = None new_msg = UserMessage(owner=article.owner, content="有人评论了你的文章《%s》" % article.title, link="/article/articledetail/%s" % article_id, status=0) new_msg.save() if form.is_valid(): comment = form.save(commit=False) comment.owner = request.user comment.article = article comment.to_comment = to_comment comment.status = 0 comment.save() status = "ok" msg = "" else: status = "err" msg = "错误信息" return json_response({"status": status, "msg": msg})
def add_comment(request, pk): user = request.user article = get_object_or_404(Article, pk=pk) if request.method == "POST" and ( user.groups.filter(name="Users").count() or user.groups.filter(name="Authors").count()): form = CommentForm(request.POST) if form.is_valid(): commentary = form.save(commit=False) commentary.article = article commentary.nick = user.profile commentary.save() return redirect('detail', pk=article.pk) else: form = CommentForm() return render(request, 'article/commentary_form.html', {'form': form})
def addcomment(request, article_id): if request.POST: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_article = Article.objects.get(id=article_id) form.save() return redirect('/article/get/%s/' % article_id)
def comment_form(obj): content_type = ContentType.objects.get_for_model(obj) form = CommentForm(initial={ 'content_type': content_type.model, 'object_id': obj.pk, 'reply_id': 0 }) return form
def comment(request, article_id): art = Article.objects.get(id=article_id) if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): comm = form.save(commit=False) comm.comment_date = timezone.now() comm.article = art comm.save() messages.success(request, "Your Comment was added") return redirect('all_articles') else: form = CommentForm() args = {} args.update(csrf(request)) args['article'] = art args['form'] = form return render(request, 'comment/comment.html', args)
def article(request, id=1): article = get_object_or_404(Article, id=id) return render( request, 'article.html', { 'article': article, 'comments': article.comment_set.all(), 'form': CommentForm(), 'username': auth.get_user(request).username, })
def add_comment(request, article_id=1): if request.POST and request.session.get("pause", True): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.article_reference = Article.objects.get(id=article_id) form.save() request.session.set_expiry(60) request.session["pause"] = False return redirect(f"/articles/{article_id}/")
def addcomment(request, article_id): if request.POST and ('pause' not in request.session): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_arcticle = Article.objects.get(id=article_id) form.save() request.session.set_expiry(60) request.session['pause'] = True return redirect('/articles/get/%s/' % article_id)
def addcomment(request, id): if 'pause' not in request.session: article = get_object_or_404(Article, id=id) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.article = article comment.save() request.session.set_expiry( 60) # кука с сессией будет актуальна 1 минуту request.session['pause'] = True # дополнительное значение в сессии return redirect('/articles/get/{}/'.format(id))
def addcomment(request, article_id): if request.POST and ("pause") not in request.session: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_acticle = Article.objects.get(id=article_id) comment.comments_date = datetime.datetime.now() form.save() request.session.set_expiry(3) request.session['pause'] = True return redirect("/get/%s" % article_id)
def addcomment(request, article_id): if request.method=='POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_article = Article.objects.get(id = article_id) if request.user.is_anonymous(): return redirect('/article/get/%s/' % article_id) else: comment.comments_from = request.user form.save() return redirect('/article/get/%s/' % article_id)
def addcomment(request, article_id): # добавление комментариев if request.POST: form = CommentForm(request.POST) username = auth.get_user(request).username if form.is_valid(): comment = form.save(commit=False) comment.comments_article = Article.objects.get(id=article_id) comment.username_comments = request.user form.save() return redirect('/articles/get/%s/' % article_id)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['views'] = r.incr("article:{}:views".format(self.kwargs['pk'])) r.zincrby('posts_ranking', int(self.kwargs['pk']), 1) posts_ranking = r.zrange('posts_ranking', 0, -1, desc=True)[:10] posts_ranking_ids = [int(id) for id in posts_ranking] most_viewed = list(ArticlePost.objects.filter(id__in=posts_ranking_ids)) most_viewed.sort(key=lambda x: posts_ranking_ids.index(x.id)) context['most_viewed'] = most_viewed # comment form context['comment_form'] = CommentForm() return context
def post_detail(request, post_id): pk = post_id # post = Post.objects.get(id=pk) post = get_object_or_404(Post, id=pk, draft=False) comments = post.comments.all() form = CommentForm(request.POST or None) print(post) context = {'post': post, 'comments': comments, 'form': form} if request.method == 'POST': if form.is_valid(): form.instance.post = post form.save() messages.add_message(request, messages.SUCCESS, 'basarili') return redirect('post_detail', post_id=post.id) return render(request, 'article/post_detail.html', context)
def comment(request): """ 文章评论 """ if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.article = ArticlePost.objects.get(pk=request.POST.get('pk')) new_comment.save() return JsonResponse({ "code": 200, 'msg': "Thanks for commenting, I will reply later.", "data": { 'name': form.cleaned_data['commentator'], 'body': form.cleaned_data['body'] }}) else: return JsonResponse({"code": 400, 'msg': "Error"})
def article_detail(request, username, article_id, **kwargs): article = Article.objects.filter(id=article_id, author__username=username) if not article: return HttpResponseNotFound() content = markdown(article[0].content) # 历史纪录 history_time_list, new_history = get_or_set_history(request, article[0].id) comment_form = CommentForm() comment_list = article[0].comment_set.all().order_by('create_time')[:5] total_comment_count = article[0].comment_set.count() response = render(request, 'article/article_detail.html', { 'article': article[0], 'content': content, 'history_time_list': history_time_list, 'tool_bar': kwargs.get('tool_bar'), 'comment_form': comment_form, 'comment_list': comment_list, 'total_comment_count': total_comment_count, }) response.set_cookie('history', new_history) return response
def add_comment(request, article_id): """ The function adds comment of the article :param request: :param article_id: :return: """ if request.POST and ('pause' not in request.session): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comments_article = Article.objects.get(id=article_id) comment.comments_date = timezone.now() if request.user.id: comment.comments_from_id = request.user.id else: return HttpResponse('Не авторизован') form.save() # Создаем объект сессии в течении 60 секунд # request.session.set_expiry(60) # request.session['pause'] = True return redirect(reverse('article:article', args=(article_id, 1)))
def add_comments_view(request): """ 添加评论 """ form = CommentForm(request.POST) if not form.is_valid(): return http_response(request, statuscode=ERRORCODE.PARAM_ERROR) nickname = form.cleaned_data.get('nickname') email = form.cleaned_data.get('email') website = form.cleaned_data.get('website') content = form.cleaned_data.get('content') target = form.cleaned_data.get('target') parent_comment_id = form.cleaned_data.get('parent_comment_id') try: user, created = Visitor.objects.update_or_create( nickname=nickname, email=email, defaults={ "nickname": nickname, "email": email, "website": website, "avatar": gravatar_url(email) }) ip_address = get_clientip(request) country, province, city = get_location_by_ip(ip_address) anchor = ''.join( random.sample(string.ascii_lowercase + string.digits, 16)) comment_data = { "user_id": user.id, "content": content, "target": target, "ip_address": ip_address, "country": country, "province": province, "city": city, "anchor": anchor, } # 二级回复 if parent_comment_id: parent_comment = Comments.objects.select_related().filter( pk=parent_comment_id).first() reply_to = parent_comment.user if parent_comment else None comment_data.update({ "parent_id": parent_comment_id, "reply_to": reply_to }) mail_body = MailTemplate.notify_parent_user.format( parent_user=parent_comment.user.nickname, parent_comment=parent_comment.content, comment_user=nickname, comment=content, target_url=DOMAIN_NAME + parent_comment.target, anchor='#' + parent_comment.anchor) send_email_task.delay(reply_to.email, mail_body) Comments.objects.create(**comment_data) cache.delete_pattern(target) # 清除缓存 if not parent_comment_id and not user.blogger: mail_body = MailTemplate.notify_blogger.format( nickname=nickname, comment=content, target_url=DOMAIN_NAME + target, anchor='#' + anchor) send_email_task.delay(BLOGGER_EMAIL, mail_body) return http_response(request, statuscode=ERRORCODE.SUCCESS) except Exception as exp: return http_response(request, statuscode=ERRORCODE.FAILED, msg=exp)