def comment(request): context = RequestContext(request) if request.method == 'DELETE': if request.user.is_authenticated(): Comment.removeComment(QueryDict(request.body).get('comment_id')) return HttpResponse(json.dumps({'msg': 'post deleted'}), content_type="application/json") else: loginError(context) elif request.method == 'POST': if request.user.is_authenticated(): author = Author.objects.get(user=request.user) guid = uuid.uuid1() comment = request.POST.get("comment", "") post = Post.objects.get(guid=request.POST.get("post_id", "")) new_comment = Comment.objects.create(guid=guid, author=author, comment=comment, post=post, pubDate=timezone.now()) return HttpResponse(json.dumps(new_comment.getJsonObj()), content_type="application/json") else: loginError(context)
def detail(request, slug): """ This views gives us detail of article which has same slug with slug and also user can comments article or comments :param request: :param slug: :return: """ article = get_object_or_404(Article, slug=slug) new_comment_form = CommentForm() # displaying comment form to the user show_comment_form = True if request.method == "POST": # create comment form new_comment_form = CommentForm(request.POST) if new_comment_form.is_valid(): # if valid taking values in the form by variables name = request.POST.get("name") email = request.POST.get("email") comment = request.POST.get("comment") content_type_id = request.POST.get("content_type_id") object_id = request.POST.get("object_id") type = ContentType.objects.get_for_id(content_type_id) # saving comment new_comment = Comment(comment=comment, email=email, name=name, content_type=type, object_id=object_id, article=article) new_comment.save() delete_cache() # controlling user is registered or not and # if s/he are not registered or logged in, # s/he needs to confirm comment check_user(email, new_comment, request) # not displaying comment form to the user return redirect("/articles/" + slug + "/#comment-" + str(new_comment.id)) else: show_comment_form = False comments, comments_of_comments, type_article, type_comment = \ find_all_comments( article ) c = { "article": article, "comments": comments, "comments_of_comments": comments_of_comments, "form": new_comment_form, "content_type_article": type_article.id, "content_type_comment": type_comment.id, "show_comment_form": show_comment_form } return render(request, "detail.html", c)
def test_get_all(self): Comment(id=5, author=self.user, post=self.post, content='New Comment').save() new_comment = Comment.objects.get(id=5) expected_comments = [self.comment, new_comment] comments = Comment.get_all(self.post) self.assertEqual(list(comments), expected_comments)
def post(self, request, *args, **kwargs): data = request.data usertags = [] for usertag_pk in data.get('tags'): try: usertag = get_user_model().objects.get(pk=usertag_pk) except get_user_model().DoesNotExist: usertag = None if usertag is not None: usertags.append(usertag) try: post = Post.objects.get(pk=data.get('post')) author = get_user_model().objects.get(pk=data.get('author')) except Post.DoesNotExist: post = None except get_user_model().DoesNotExist: author = None if post is not None and author is not None: comment = Comment( post=post, author=author, content=data.get('content'), usertags=usertags, ) comment.save() return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Invalid pk values"})
def create_comment(request): if not request.user.is_authenticated(): return json_response({"status": "error", "msg": "您没有登录,不能发表评论哦~"}) article_id = int(request.POST["article_id"]) to_comment_id = int(request.POST.get("to_comment_id", 0)) content = request.POST["content"].strip() if not content: return json_response({"status": "error", "msg": "评论内容不能为空."}) article = Article.objects.get(id=article_id) if to_comment_id != 0: to_comment = Comment.objects.get(id=to_comment_id) new_msg = UserMessage(owner=to_comment.owner, content=u"有人回复了你的评论'%s'" % to_comment.content[:30], link="http://%s/article/detail/%s" % (request.get_host(), article.id)) new_msg.save() else: to_comment = None new_msg = UserMessage(owner=article.owner, content=u"有人评论了您的文章《%s》" % article.title, link="http://%s/article/detail/%s" % (request.get_host(), article.id)) new_msg.save() comment = Comment(article=article, owner=request.user, content=content, to_comment=to_comment) comment.save() return json_response({"status": "ok", "msg": ""})
def update_comment(request): referer = request.META.get('HTTP_REFERER', reverse('home')) comment_form = CommentForm(request.POST, user=request.user) data = {} if comment_form.is_valid(): # 检查通过,保存数据 comment = Comment() comment.user = comment_form.cleaned_data['user'] comment.text = comment_form.cleaned_data['text'] comment.content_object = comment_form.cleaned_data['content_object'] parent = comment_form.cleaned_data['parent'] if not parent is None: comment.root = parent.root if not parent.root is None else parent comment.parent = parent comment.reply_to = parent.user comment.save() # 返回数据 data['status'] = 'SUCCESS' data['username'] = comment.user.username data['comment_time'] = comment.comment_time.timestamp() data['text'] = comment.text if not parent is None: data['reply_to'] = comment.reply_to.username else: data['reply_to'] = '' data['pk'] = comment.pk data['root_pk'] = comment.root.pk if not comment.root is None else '' else: #return render(request, 'error.html', {'message': comment_form.errors, 'redirect_to': referer}) data['status'] = 'ERROR' data['message'] = list(comment_form.errors.values())[0][0] return JsonResponse(data)
def detail(request, posts_id): """" 根据模板页传递的,id查询详情文章""" posts = get_object_or_404(Posts, pk=posts_id) # markdown 模块支持,渲染详情页 posts.content = markdown.markdown(posts.content, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) # 获取这篇 post 下的全部评论 comment_list = Comment.objects.filter(posts_id=posts.pk) # 将文章、表单、以及文章下的评论列表作为模板变量传给 detail.html 模板,以便渲染相应数据。 context = {'posts': posts, 'comment_list': comment_list} # get请求是登录界面进入时发生 if request.method == "GET": posts.increase_views() return render(request, 'front/detail.html', context=context) # post请求是提交登录表单的时候 elif request.POST: content = request.POST.get('content') if context: comment = Comment(author=posts.users.nickname, email=posts.users.email, content=content, created_time=timezone.now(), posts_id=posts.pk) comment.save() posts.increase_comment_num() # 重定向到评论的文章 return render(request, 'front/detail.html', context=context)
def index(request): if request.method == "POST" and "postid" in request.POST: postid = request.POST['postid'] name = request.POST['name'] email =request.POST['email'] comments = request.POST['comment'] comment = Comment(postid=postid,name=name,email=email,comment=comments) comment.save() username = comment.name data= { 'name': comment.name, 'comment': comment.comment, 'response' : "sussecsful" } json_data = json.dumps(data) return HttpResponse(json_data) return HttpResponse()
def update_comment(request): referer = request.META.get('HTTP_REFERER', reverse('index')) comment_form = CommentForm(request.POST, user=request.user) data = {} if comment_form.is_valid(): comment = Comment() comment.user = comment_form.cleaned_data['user'] comment.text = comment_form.cleaned_data['text'] comment.content_object = comment_form.cleaned_data['content_object'] parent = comment_form.cleaned_data['parent'] if not parent is None: comment.root = parent.root if not parent.root is None else parent comment.parent = parent comment.reply_to = parent.user comment.save() data['status'] = 'success' data['username'] = comment.user.username data['comment_time'] = comment.comment_time.strftime( '%Y-%m-%d %H:%M:%S') data['text'] = comment.text data['content_type'] = ContentType.objects.get_for_model(comment).model if not parent is None: data['reply_to'] = comment.reply_to.username else: data['reply_to'] = '' data['pk'] = comment.pk data['root_pk'] = comment.root.pk if not comment.root is None else '' else: # return render(request, 'error.html', {'message': comment_form.errors,'redirect_to': referer}) data['status'] = 'error' data['message'] = list(comment_form.errors.values())[0][0] return JsonResponse(data)
def create(self, request, *args, **kwargs): post = get_object_or_404(self.get_queryset(), id=kwargs['pk']) comment = Comment(content=request.data['content'], user_profile=request.user.user_profile, post=post) comment.save() return Response(self.get_serializer(comment).data)
def create_comment(request): if not request.user.is_authenticated(): return json_response({'status': 'error', 'msg': '您没有登陆,不能发表评论哦'}) article_id = int(request.POST["article_id"]) to_comment_id = int(request.POST.get('to_comment_id', 0)) content = request.POST['content'].strip() if not content: return json_response({'status': 'error', 'msg': '评论内容不能为空'}) article = Article.objects.get(id=article_id) 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="http://%s/article/articledetail/%s" % (request.get_host(), article_id)) new_msg.save() else: to_comment = None new_msg = Usermessage(owner=article.owner, content="有人评论了你的文章《%s》" % article.title, link="http://%s/article/articledetail/%s" % (request.get_host(), article.id)) new_msg.save() comment = Comment(article=article, owner=request.user, content=content, to_comment=to_comment) comment.save() return json_response({'status': 'ok', 'msg': ''})
def comment_create(request): article_id = int(request.POST["article_id"]) to_comment_id = int(request.POST["to_comment_id"]) content = request.POST["content"] page_nums = request.POST["page_nums"] article = Article.objects.get(id=article_id) block = article.block owner = request.user comment = Comment(block=block, article=article, owner=owner, to_comment_id=to_comment_id, content=content) comment.save() if to_comment_id == 0: msg = UserMessage( owner=article.author, content=u"有人评论了你的文章:《%s》" % article.title, link=reverse("article_display", args=[article.id]) + "?comment_no=" + page_nums, ) msg.save() else: to_comment = Comment.objects.get(id=to_comment_id) msg = UserMessage( owner=to_comment.owner, content=u"有人评论了你的评论:'%s'" % to_comment.content[:20], link=reverse("article_display", args=[article.id]) + "?comment_no=" + page_nums, ) msg.save() return response.json_response({})
def ifstatus(request): article_id = request.POST["article_id"] article_id = json.loads(article_id) info_link = request.POST["info_link"] content = request.POST["content"] page_number = request.POST["page_number"] pahe_number = json.loads(page_number) owner = request.user article = Article.objects.get(id=article_id) to_comment_id = int(request.POST.get("to_comment_id", 0)) if to_comment_id != 0: to_comment = Comment.objects.get(id=to_comment_id) info_content = "有人回复了你的评论'%s'" % (to_comment) info_link = info_link + "?page_no=%s" % (page_number) else: to_comment = None info_content = "有人回复了你的文章'%s'" % (article.title) info_link = info_link if not content: return json_response({"status": "no", "msg": "输入内容为空"}) else: information = Information(owner=article.owner, content=info_content, link=info_link, status=-1) information.save() comment = Comment(owner=owner, article=article, content=content, to_comment=to_comment, status=0) comment.save() return json_response({"status": "ok", "msg": "评论成功"})
def comment(request): if request.method == "POST": article_id = request.POST['article_id'] content = request.POST['content'].strip() to_comment_id = int(request.POST.get("to_comment_id", 0)) article = Article.objects.get(id=article_id) user = request.user if not content: return json_response({"status": "err", "msg": "内容不能为空"}) if to_comment_id != 0: to_comment = Comment.objects.get(id=to_comment_id) else: to_comment = None c = Comment(owner=user, article=article, content=content, status=0, to_comment=to_comment) c.save() link = "http://%s/article/detail/%s" % (request.get_host(), article_id) print(link) contents = "有人评论你‘" + content + "'" m = Message(owner=user, content=contents, link=link, status=1) m.save() return json_response({"status": "ok", "msg": ""}) else: return render(request, "article/article_detail.html")
def form_valid(self, form): app_name = self.app_name model_name = self.model_name model_id = self.model_id model_object = get_model_obj(app_name, model_name, model_id) parent_id = self.parent_id parent_comment = Comment.objects.get_parent_comment(parent_id) user = get_user_for_request(self.request) comment_content = form.cleaned_data['content'] email = form.cleaned_data.get('email', None) or user.email time_posted = timezone.now() comment = Comment(content_object=model_object, content=comment_content, user=user, parent=parent_comment, email=email, posted=time_posted) if settings.COMMENT_ALLOW_ANONYMOUS and not user: # send response, please verify your email to post this comment. response_msg = process_anonymous_commenting(self.request, comment) messages.info(self.request, response_msg) else: comment.save() self.comment = comment return self.render_to_response(self.get_context_data())
def test_get_author_returns_present_author_or_guest_name(self): cases = [(self.author, None), (None, self.guest_name)] for (author, guest_name) in cases: comment = Comment( post=self.post, author=author, guest_name=guest_name, body=self.body) self.assertEqual(comment.get_author(), author or guest_name)
def update_comment(request): data = {} comment_form = CommentForm(request.POST, user=request.user) if comment_form.is_valid(): # 检查通过,保存数据 comment = Comment() comment.user = comment_form.cleaned_data['user'] comment.text = comment_form.cleaned_data['text'] comment.content_object = comment_form.cleaned_data['content_object'] parent = comment_form.cleaned_data['parent'] if parent: comment.root = parent.root if parent.root else parent comment.parent = parent comment.reply_to = parent.user comment.save() #评论/回复成功,返回数据 data['status'] = 'SUCCESS' data['username'] = comment.user.get_nickname_or_username() data['comment_time'] = comment.comment_time.strftime( '%Y-%m-%d %H:%M:%S') data['text'] = comment.text data['reply_to'] = comment.reply_to.get_nickname_or_username( ) if parent else None data['id'] = comment.id data['root_id'] = comment.root.id if parent else None data['content_type'] = ContentType.objects.get_for_model(comment).model # 评论/回复失败 else: data['status'] = 'ERROR' data['message'] = list(comment_form.errors.values())[0][0] return JsonResponse(data)
def update_comment(request): """更新评论视图函数""" referer = request.META.get('HTTP_REFERER', reverse('blog: index')) comment_form = CommentForm(request.POST, user=request.user) if comment_form.is_valid(): comment = Comment() comment.user = comment_form.cleaned_data['user'] comment.text = comment_form.cleaned_data['text'] comment.content_object = comment_form.cleaned_data['content_object'] parent = comment_form.cleaned_data['parent'] if not parent is None: comment.root = parent.root if not parent.root is None else parent comment.parent = parent comment.reply_to = parent.user comment.save() # 发送站内通知 # 判断评论时博客还是 # if comment.reply_to is None: # # 接收者是文章 # recipient = comment.content_object.get_user() # if comment.content_type.model == 'post': # blog = comment.content_object # verb = '{0}评论了你的<<{1}>>'.format(comment.user, blog.title) # else: # raise Exception('不明评论') # else: # recipient = comment.reply_to # verb = '{0}评论类了你的评论{1}'.format(comment.user, strip_tags(comment.parent.text)) # notify.send(comment.user, recipient=recipient, verb=verb, action_object=comment) return redirect(referer + '$comment')
def create(self, request, *args, **kwargs): review = Review.objects.get(id=kwargs['pk']) comment = Comment(author=self.request.user, review=review, content=self.request.data['content']) comment.save() return Response(self.get_serializer(comment).data)
def test_model_unicode_trims_spaces_and_punctuation(self): word = self.faker.word() punctuation = ' .' comment = Comment( post=self.post, author=self.author, guest_name=self.guest_name, body=word + punctuation * (80 / len(punctuation))) self.assertEqual(comment.__unicode__()[:-3], word)
def topicomment(request): if request.is_ajax() and request.method == 'POST': # print request.POST.get('comment') text = request.POST.get('comment') topicid = request.POST.get('topicid') topic = Topic.objects.get(pk=topicid) # print request.POST.get('comment') # print request.POST.get('topicid') user = request.user # print user try: c = Comment(user=user, topic=topic, text=text) c.save() if topic.writer != user: notify.send(sender=user, target_object= None , recipient = topic.writer, verb='#' , text=text, target_article = None , target_products = None , target_topic = topic) cachekey = "user_unread_count" + str(topic.writer.id) if cache.get(cachekey) != None: cache.incr(cachekey) else: unread = Notification.objects.filter(recipient = topic.writer).filter(read = False).count() cache.set(cachekey, unread, settings.CACHE_EXPIRETIME) topic.updated = timezone.now() instancesave.delay(topic) cachekey = "topic_comment_" + str(topicid) if cache.get(cachekey) != None: cache.incr(cachekey) else: cache.set(cachekey, topic.comment_set.count(), settings.CACHE_EXPIRETIME) userlist = atwho(text = text, sender = user, targetcomment = None, targetproducts = None , targetarticle = None, targetopic = topic) for item in userlist: atwhouser = MyUser.objects.get(username = item) # test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' # text = text.replace('@'+item+' ', test); test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' test1 = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' text = text.replace('@'+item+' ', test); text = text.replace('@'+item+' ', test1); # c = Comment(user=user, topic=topic, text=text) # c.save() data = { "user": user.username, "text": text, "commentid": c.id } # print data['commentid'] json_data = json.dumps(data) print 'data' return HttpResponse(json_data, content_type='application/json') except: traceback.print_exc() raise Http404(traceback) else: raise Http404
def save(request): if request.user.is_authenticated(): if 'text' in request.POST: pub_id = Publication.objects.get(id=request.POST.get('id')) us = request.user comment = Comment(text=request.POST.get('text'), publication=pub_id, user=us) comment.save() return get_ajax_comments(request, pub_id) return HttpResponse('wrong!')
def add_replied(request): isMobile = dmb.process_request(request) if request.user.is_anonymous(): return comm.redirect_login_path(isMobile, request) result = {} if request.method == 'POST': if 'kbid' in request.POST and 'content' in request.POST and 'currentcommentid' in request.POST: kbid = request.POST['kbid'] content = request.POST['content'] currentcommentid = request.POST['currentcommentid'] try: kb = Article.objects.get(pk=kbid) try: comment_old = Comment.objects.get(pk=currentcommentid) comment = Comment(commenter=request.user, kb=kb, date=timezone.now(), type=1, content=content, replied_comment=comment_old) comment.save() kb.count_reply = kb.comment_set.all().count() kb.save() result['status'] = 'OK' result['msg'] = '评论成功...' except Comment.DoesNotExist: sys_log.warnging('Comment.DoesNotExist error') result['status'] = 'ERROR' result['msg'] = '错误1...' except Article.DoesNotExist: sys_log.warnging( '[Article.DoesNotExist]add replied comment request parameter error in POST' ) result['status'] = 'ERROR' result['msg'] = '错误2...' except Article.MultipleobjectReturned: sys_log.warnging( '[Article.MultipleobjectReturned]add replied comment request parameter error in POST' ) result['status'] = 'ERROR' result['msg'] = '错误3...' else: sys_log.warnging( 'add replied comment request parameter error in POST') result['status'] = 'ERROR' result['msg'] = '错误4...' else: sys_log.warnging('add replied comment request method error') result['status'] = 'ERROR' result['msg'] = '错误5...' return HttpResponse(json.dumps(result), content_type='application/json')
def add(request): context = {} user_id = request.POST['user_id'] post_id = request.POST['post_id'] text = request.POST['text'] time = datetime.time comment = Comment(user_id = user_id,post_id = post_id,text = text,time = time) comment.save() return redirect('/post/detail/'+post_id)
def comment_block(target): print('32') print(target) print(Comment.get_by_target(target)) return { 'target': target, 'comment_form': CommentForm(), 'comment_list': Comment.get_by_target(target), }
def comment(): global postID, commentText commentForm = CommentForm() commentFormAfterCheck = CommentFormAfterCheck() # We come here twice, from different forms, only use it once. if 'postID' in request.form: postID = request.form['postID'] if commentForm.validate_on_submit(): commentText = commentForm.commentText.data response = requests.post(urlsConfig.URLS['profanity_url'], params={'text': commentText}) # Only show div is post contained a bad word if response.text == "BAD": return render_template("comment.html", title="Comment", commentForm=commentForm, commentFormAfterCheck=commentFormAfterCheck, display='') elif response.text == "GOOD": comment = Comment(commentText=commentText, user="******", postID=postID, timestamp=datetime.now()) commentDB.session.add(comment) commentDB.session.commit() print("Successfully placed a comment!") return redirect(urlsConfig.URLS['newsfeed_url']) if commentFormAfterCheck.validate_on_submit(): if commentFormAfterCheck.submitAfterCheck.data: comment = Comment(commentText=commentText, user="******", postID=postID, timestamp=datetime.now()) commentDB.session.add(comment) commentDB.session.commit() flash("Successfully created a new comment!") return redirect(urlsConfig.URLS['newsfeed_url']) elif commentFormAfterCheck.discardAfterCheck.data: print("Pressed discard") return redirect(url_for("comment")) else: pass return render_template("comment.html", title="Comment", commentForm=commentForm, commentFormAfterCheck=commentFormAfterCheck, display='none')
def update_comment(request): refer = request.META.get('HTTP_REFERER', reverse('article:home')) form = CommentForms(request.POST) data = {} if form.is_valid(): aid = request.POST.get('aid') print("aid=", aid) comment = Comment() # comment = Us comment.name = form.cleaned_data['name'] comment.email = form.cleaned_data['email'] comment.article = Article.objects.get(id=aid) comment.context = form.cleaned_data['context'] parent_id = form.cleaned_data['parent_id'] if parent_id != -1: comment.parent = Comment.objects.get(id=parent_id) comment.save() # 返回的参数 data['status'] = 'success' data['username'] = request.user.username data['comment_time'] = comment.created_time.strftime( '%Y-%m-%d %H-%M-%S') data['text'] = comment.context data['commnet_id'] = comment.id print(data) else: data['status'] = 'Error' data['message'] = list(form.errors.values())[0][0] # 以Json的形式返回数据 return JsonResponse(data)
def answer_create(request, board_id): if not request.session.get('user'): return redirect('/auth/login') board = get_object_or_404(Board, pk=board_id) user_id = request.session.get('user') member = User.objects.get(pk=user_id) comment = Comment(board=board, content=request.POST.get('content'), create_date=timezone.now(), writer=member) comment.save() return redirect('board:detail', pk=board.id)
def initialize_comments(self): # 만약 article_id가 articles_data에서의 index + 1 이 아니면 엉뚱한 댓글이 사용될 수 있음! for article_id, article_data in enumerate(self.articles_data, 1): for comment in article_data['comments']: comment_instance = Comment(article_id=article_id, author_id=random.choice( self.users).username, content=comment['content'], parent_id=None) comment_instance.save() self.comments.append(comment_instance) print("Create random comments. ", comment_instance)
def post(self, request, article_id): if request.user.id: article_id = request.POST['article_id'] user_id = request.user.id comment = request.POST['comment'] com = Comment(article_id=article_id, user_id=user_id, comment=comment) com.save() return self.get(request, article_id) else: return redirect(reverse('user:login'))
def comment(request, account_id, post_id): if request.POST: comment = Comment( post_id=post_id, author=Account.objects.get(id=request.POST['user_id']).username, comment_text=request.POST['comment_text']) comment.save() return HttpResponseRedirect( reverse('detail', kwargs={ 'account_id': account_id, 'post_id': post_id }))
def comment(request, pk): u_id = request.session['user'] com = Comment.objects.filter(u_id=u_id, b_id=pk) if com: return redirect('blog:detail', pk=pk) b_id = pk c_content = request.POST.dict()['comment'] com = Comment(u_id=u_id, b_id=b_id, c_create_time=datetime.now(), c_content=c_content) com.save() return redirect('blog:detail', pk=pk)
def add_comment(request, post_id, page): if request.method == 'POST': try: post = Post.objects.get(id=post_id) except: return render(request, 'error.html', {'code': '404'}) new_comment = Comment(comment=request.POST['comment'], author=request.user) new_comment.save() post.comments.add(new_comment) if page == 'profilePage': return HttpResponseRedirect(reverse(page, args=(post.user.id, ))) return HttpResponseRedirect(reverse(page))
def productscommentcomment(request): if request.is_ajax() and request.method == 'POST': print 'commentcomment' text = request.POST.get('comment') productsid = request.POST.get('productsid') #parenttext = request.POST.get('parenttext') preentid = request.POST.get('preentid') products = Products.objects.get(pk=productsid) #comment = Comment.objects.filter(products=products) targetcomment = Comment.objects.get(pk=preentid) user = request.user if targetcomment.user == user: pass; else: receiver = targetcomment.user.username text="@"+receiver+" "+text try: c = Comment(user=user, products=products, text=text, parent=targetcomment) c.save() #文章回复数量缓存 增加1 cachekey = "products_comment_" + str(productsid) if cache.get(cachekey) != None: cache.incr(cachekey) else: cache.set(cachekey, products.comment_set.count(), settings.CACHE_EXPIRETIME) #被评论的评论readers+1放到消息队列中 readersin.delay(targetcomment) #返回@用户的列表,并向@的用户发送消息 userlist = atwho(text = text, sender = user, targetcomment = targetcomment, targetarticle = None , targetproducts = products, targetopic = None ) #给被@的用户增加链接 for item in userlist: print 'for item in userlist:' atwhouser = MyUser.objects.get(username = item) test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' text = text.replace('@'+item+' ', test); data = { "user": user.username, "text": text, "parentcommentext": c.parent.text, "parentcommentuser": str(c.parent.user), "commentid":c.id, } json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json') except: traceback.print_exc() raise Http404(traceback) else: raise Http404
def update_comment(request): # if not request.user.is_authenticated: # return HttpResponse('未登录') # text = request.POST.get('text', '').strip() # if text == '': # return HttpResponse('不能为空') # try: # content_type = request.POST.get('content_type', '') # object_id = int(request.POST.get('object_id', '')) # model_class = ContentType.objects.get(model=content_type).model_class() # model_obj = model_class.objects.get(id=object_id) # except Exception as e: # return HttpResponse('出错') # comment = Comment() # comment.user = request.user.userprofile # comment.text = text # comment.content_object = model_obj # comment.save() # referer = request.META.get('HTTP_REFERER', '/') # return redirect(referer) referer = request.META.get('HTTP_REFERER', '/') data = {} comment_form = CommentForm(request.POST, user=request.user) if comment_form.is_valid(): comment = Comment() comment.user = request.user.userprofile comment.text = comment_form.cleaned_data['text'] comment.content_object = comment_form.cleaned_data['content_object'] parent = comment_form.cleaned_data['parent'] if parent is not None: comment.root = parent.root if parent.root is not None else parent comment.parent = parent comment.reply_to = parent.user comment.save() data['status'] = 'SUCCESS' data['user_name'] = comment.user.name data['user_head'] = str(comment.user.image) data['comment_time'] = comment.comment_time.strftime('%Y-%m-%d %H:%M') data['text'] = comment.text data['content_type'] = ContentType.objects.get_for_model(comment).model if parent is not None: data['reply_to'] = comment.reply_to.name else: data['reply_to'] = '' data['pk'] = comment.id data['root_pk'] = comment.root.id if comment.root is not None else '' else: data['status'] = 'ERROR' data['message'] = list(comment_form.errors.values())[0][0] return JsonResponse(data)
def create_comment(request): parent_id = request.POST['parent'] try: if parent_id == "0": parent = None else: parent = Comment.objects.get(id=parent_id) comment = Comment() comment.parent = parent comment.text = request.POST['text'] comment.save() except: raise Http404 return comment.id
def add_replied(request): isMobile = dmb.process_request(request) result = {} if request.user.is_anonymous(): result['status'] = 'LOGIN' else: if request.method == 'POST': if 'kbid' in request.POST and 'content' in request.POST and 'currentcommentid' in request.POST: kbid = request.POST['kbid'] content = request.POST['content'] currentcommentid = request.POST['currentcommentid'] try: kb = Article.objects.get(pk = kbid) try: comment_old = Comment.objects.get(pk = currentcommentid) comment = Comment(commenter = request.user, kb = kb, date = timezone.now(), type =1, content = content, replied_comment=comment_old) comment.save() kb.count_reply = kb.comment_set.all().count() kb.save() result['status'] = 'OK' result['msg'] = '评论成功...' except Comment.DoesNotExist: sys_log.warnging('Comment.DoesNotExist error') result['status'] = 'ERROR' result['msg'] = '错误1...' except Article.DoesNotExist: sys_log.warnging('[Article.DoesNotExist]add replied comment request parameter error in POST') result['status'] = 'ERROR' result['msg'] = '错误2...' except Article.MultipleobjectReturned: sys_log.warnging('[Article.MultipleobjectReturned]add replied comment request parameter error in POST') result['status'] = 'ERROR' result['msg'] = '错误3...' else: sys_log.warnging('add replied comment request parameter error in POST') result['status'] = 'ERROR' result['msg'] = '错误4...' else: sys_log.warnging('add replied comment request method error') result['status'] = 'ERROR' result['msg'] = '错误5...' return HttpResponse(json.dumps(result), content_type='application/json')
def createEventComment(request): event_id = request.POST['event_id'] e = get_object_or_404(Event, id=event_id) if request.POST['message'] != "": c = Comment(user=request.user, message=request.POST['message'], event=e) try: c.save() except Exception as err: messages.error(request, "Error: %s" % err) else: messages.error(request, "Error: Please don't submit the field blank!") return HttpResponseRedirect(resolve_url(request.POST['next']))
def new_comment_api(request): if request.method == "POST" and request.user.is_authenticated: articleID = request.POST['article_id'] article = News.objects.get(pk=articleID) content = request.POST['content'] comment = Comment(article=article, account=request.user, content=content) comment.save() new_comment_id = comment.pk new_comment_date = comment.publish data = [] data.append(new_comment_id) data.append(new_comment_date) return JsonResponse(data, safe=False)
def add_comment(request): if request.is_ajax(): comment = Comment(text=request.POST.get('comment-text', None), user_id=request.user.id, time=datetime.now()) comment.save() CommentEvent(comment_id=comment.id, event_id=request.POST.get('event', None)).save() results = [] comment_json = {} comment_json['addedtime'] = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') comment_json['user'] = request.user.username results.append(comment_json) data = json.dumps(results) mimetype = 'application/json' return HttpResponse(data, mimetype)
def GET(self, post_url=None): try: import hashlib post_id = post_url post = Post.get_by_id(int(post_id)) if not post: raise web.notfound() fullpath = web.ctx.home + web.ctx.fullpath check = "%s%s" % (fullpath, post.key()) checksum = hashlib.sha1(check).hexdigest() comments_query = Comment.all().filter('post =', post) if blog.comment_sort == 'asc': comments_query.order('created') else: comments_query.order('-created') comments = comments_query.fetch(blog.comment_pagesize) return render('theme/show.html', post=post, checksum=checksum, comments=comments) except: raise web.notfound()
def GET(self, comment_id = None): if comment_id: comment = Comment.get_by_id(int(comment_id)) comment.delete() clear_cache() return web.seeother('/admin/comments')
def topcommentcomment(request): if request.is_ajax() and request.method == 'POST': text = request.POST.get('comment') topicid = request.POST.get('topicid') #parenttext = request.POST.get('parenttext') preentid = request.POST.get('preentid') topic = Topic.objects.get(pk=topicid) comment = Comment.objects.filter(topic=topic) targetcomment = Comment.objects.get(pk=preentid) user = request.user print user try: c = Comment(user=user, topic=topic, text=text, parent=targetcomment) c.save() topic.updated = timezone.now() topic.save() cachekey = "topic_comment_" + str(topicid) if cache.get(cachekey) != None: cache.incr(cachekey) else: cache.set(cachekey, topic.comment_set.count(), settings.CACHE_EXPIRETIME) targetcomment.readers = targetcomment.readers + 1 targetcomment.save() userlist = atwho(text = text, sender = user, targetcomment = targetcomment , targetarticle = None, targetopic = topic) for item in userlist: atwhouser = MyUser.objects.get(username = item) test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' text = text.replace('@'+item+' ', test); # c = Comment(user=user, topic=topic, text=text, parent=targetcomment) # c.save() print 'z' data = { "user": user.username, "text": text, "parentcommentext": c.parent.text, "parentcommentuser": str(c.parent.user), "commentid":c.id, } json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json') except: traceback.print_exc() raise Http404(traceback) else: raise Http404
def responses_to_comments(): for pk, fields in respuestas.iteritems(): c = Comment() c.comment = fields['content'] c.published = True c.content_object = Dateo.objects.get(pk=fields['map_items'][0]) c.object_id = fields['map_items'][0] c.user_id = get_user(fields['user']) c.client_domain = datea c.save() created = date_parser(fields['created']) Comment.objects.filter(pk=c.pk).update(created=created)
def articlecomment(request): if request.is_ajax() and request.method == 'POST': text = request.POST.get('comment')#评论的内容 articleid = request.POST.get('articleid') article = Article.objects.get(pk=articleid) user = request.user try: c = Comment(user=user, article=article, text=text) c.save() #文章回复数量redis缓存 增加1 cachekey = "article_comment_" + str(articleid) if cache.get(cachekey) != None: cache.incr(cachekey) else: cache.set(cachekey, article.comment_set.count(), settings.CACHE_EXPIRETIME) #返回@用户的列表,并向@的用户发送消息 userlist = atwho(text = text, sender = user , targetcomment = None, targetarticle = article, targetproducts = None , targetopic = None) #给被@的用户增加链接 for item in userlist: print 'for item in userlist:' atwhouser = MyUser.objects.get(username = item) # test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' # text = text.replace('@'+item+' ', test); test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' test1 = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' text = text.replace('@'+item+' ', test); text = text.replace('@'+item+' ', test1); data = { "user": user.username, "text": text, "commentid": c.id } json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json') except: traceback.print_exc() raise Http404(traceback) else: raise Http404
def create_comments(): Comment.objects.all().delete() for pk, fields in comentarios.iteritems(): c = Comment(pk=pk) c.comment = fields['comment'] c.published = fields['published'] c.user_id = get_user(fields['user']) c.content_object = Dateo.objects.get(pk=fields['object_id']) c.object_id = fields['object_id'] c.client_domain = datea c.save() created = date_parser(fields['created']) Comment.objects.filter(pk=c.pk).update(created=created)
def index(request, lang): data = {'lang': lang} if lang not in LANGUAGES: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) contact_info = ContactInfo.objects.all() if contact_info: data['contact_info'] = contact_info[0] comments = Comment.objects.filter(deleted=False).order_by('-date') data['comments'] = comments order = '' if lang == 'es': order = 'spanish_name' elif lang == 'en': order = 'english_name' elif lang == 'de': order = 'german_name' elif lang == 'pt': order = 'portuguese_name' elif lang == 'fr': order = 'french_name' services_list = Service.objects.filter(deleted=False).order_by(order) data['services'] = services_list if request.method == 'POST': if 'btn_comment' in request.POST: content = request.POST['text_comment'] comment = Comment(content=content) comment.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_suggestion' in request.POST: content = request.POST['text_suggestion'] suggestion = Suggestion(content=content) suggestion.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_request' in request.POST: content = request.POST['request'] contact_info = request.POST['contact_info'] req = Request(content=content, contact_info=contact_info) req.save() return HttpResponseRedirect('/services/' + lang) return render_to_response('client/main/index.html', {'data': data}, RequestContext(request))
def add_comment (request, comment_id): comment = Comment () comment.id_blog = BlogRecord (id = int (comment_id) ) comment.name = request.GET[u'name'] comment.comment = request.GET[u'comment'] comment.save () return HttpResponse ('<div style = "color: green">Comment add!</div>')
def comment_view(request): contenttype = request.POST.get('content_type') comment = Comment() if contenttype == 'essay': object_pk = request.POST.get('object_pk') content_object = Essay.objects.get(id=object_pk) comment.content_object = content_object comment.nickname = request.POST.get('name') comment.email = request.POST.get('email') comment.url = request.POST.get('url') comment.content = request.POST.get('content') comment.save() url = '/home/essay/detail/%s/' % object_pk return HttpResponseRedirect(url) return HttpResponse('error')
def add_fresh(request): isMobile = dmb.process_request(request) result = {} if request.user.is_anonymous():# result['status'] = 'LOGIN' else: if request.method == 'POST': if 'kbid' in request.POST and 'content' in request.POST: kbid = request.POST['kbid'] content = request.POST['content'] try: kb = Article.objects.get(pk = kbid) comment = Comment(commenter = request.user, kb = kb, date = timezone.now(), content = content) comment.save() kb.count_reply = kb.comment_set.all().count() kb.save() ''' if request.user != kb.author: add_msg(request, kb, content) ''' result['status'] = 'OK' result['msg'] = '评论成功...' except Article.DoesNotExist: sys_log.warnging('[Article.DoesNotExist]add fresh comment request parameter error in POST') except Article.MultipleobjectReturned: sys_log.warnging('[Article.MultipleobjectReturned]add fresh comment request parameter error in POST') else: sys_log.warnging('add fresh comment request parameter error in POST') else: sys_log.warnging('add fresh comment request method error') pdb.set_trace() return HttpResponse(json.dumps(result), content_type='application/json')
def comment(request): global username r = Comment.objects.all() if request.POST: f = CommentForm(request.POST) if f.is_valid(): if 'delete' in request.POST: print(username) if username == request.user: print(123) r.delete() else: user = f.cleaned_data['user'] content = f.cleaned_data['content'] email = f.cleaned_data['email'] date_time = datetime.datetime.now() c = Comment(user=user, email=email, content=content, date_time=date_time) c.save() f = CommentForm() else: f = CommentForm() return render_to_response('comments.html',RequestContext(request,locals()))
def post(request): """ 提交评论 """ # 返回信息 msg = '评论成功!' # 验证GET或POST if request.method == 'GET': msg = '不要乱玩哦亲:提交方式为GET' return HttpResponse(msg, 'application/javascript') post = request.POST # 取得文章 post_id = post.get('post_id', None) if not post_id: msg = '不要乱玩哦亲:post_id为空' return HttpResponse(msg, 'application/javascript') posts = Posts.objects.get(id=post_id) # 处理账号信息 author = post.get('author', '屁民') email = post.get('email', '') url = post.get('url', '') user = User() try: user = User.objects.get(first_name=author, email=email) except User.DoesNotExist: # 生成一个不重复和username username = uuid.uuid1() user.username = username user.first_name = author user.email = email user.last_name = url user.save() # 处理评论 contact = post.get('comment', None) if not contact or contact.strip() == '': msg = '评论不能为空哦!' return HttpResponse(msg, 'application/javascript') comment = Comment() comment.contact = contact comment.user = user comment.post = posts comment.save() # 返回信息 return HttpResponse('SUCCESS', 'application/javascript')
def get_post_json(post): post_json = post.getJsonObj() comment_list = [] comments = Comment.getCommentsForPost(post) for comment in comments: comment_list.append(comment.getJsonObj()) category_list = [] categories = PostCategory.getCategoryForPost(post) if categories is not None: for category in categories: category_list.append(category.name) post_json['comments'] = comment_list post_json['categories'] = category_list return post_json
def body(self): content = memcache.get('widget_comments') if not content: comments = Comment.all().order('-created').fetch(10) content = [] write = content.append write('<ul>') for comment in comments: write("""<li> <span class="author"><a href="%s" target="_blank">%s</a></span> <a href="%s#cmt">%s</a> </li>""" % (comment.homepage, comment.name, comment.post.getUrl(), comment.content)) write('</ul>') content = '\n'.join(content) memcache.set('widget_comments', content) return content
def post_view(request, post_slug, post_id): post = Post.get(post_id) if not post: raise Http404('The post could not be found') if post.status != 'PUBLISHED' and post.user_id != request.user.id \ or post.slug != post_slug: raise Http404('The post could not be found.') comments = Comment.get_comments(post) if post.status != 'DRAFT': comment_form = request.user.is_authenticated() and\ AuthorizedCommentForm or AnonymousCommentForm comment_form = comment_form(initial={ 'root_ctype_id': ContentType.objects.get_for_model(Post).id, 'root_object_id': post.id, 'next_page': reverse('post', args=[post.slug, post.id])}) else: comment_form = None return render(request, 'post/view.html', {'post': post, 'comments': comments, 'comment_form': comment_form})
def services(request, lang): contact_info = ContactInfo.objects.all() comments = Comment.objects.filter(deleted=False).order_by('-date') data = {'lang': lang, 'comments': comments} if contact_info: data['contact_info'] = contact_info[0] if lang not in LANGUAGES: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) order = '' if lang == 'es': order = 'spanish_name' elif lang == 'en': order = 'english_name' elif lang == 'de': order = 'german_name' elif lang == 'pt': order = 'portuguese_name' elif lang == 'fr': order = 'french_name' if 'service' in request.GET: id = request.GET['service'] error = False for x in range(0, len(str(id))): if not str(id)[x].isdigit(): error = True break if not error: services_list = Service.objects.filter(deleted=False, id=int(id)).order_by(order) if not services_list: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) images = Image.objects.filter(deleted=False, service=services_list[0]) if images: position = random.randrange(0, images.count()) data['image'] = images[position] data['selected'] = True data['service'] = id else: return render_to_response('client/404.html', {'data': data}, RequestContext(request)) else: services_list = Service.objects.filter(deleted=False).order_by(order) images = Image.objects.filter(deleted=False) if images: position = random.randrange(0, images.count()) data['image'] = images[position] data['services'] = services_list data['images'] = images if request.method == 'POST': if 'btn_comment' in request.POST: content = request.POST['text_comment'] comment = Comment(content=content) comment.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_suggestion' in request.POST: content = request.POST['text_suggestion'] suggestion = Suggestion(content=content) suggestion.save() return HttpResponseRedirect('/services/' + lang) elif 'btn_request' in request.POST: content = request.POST['request'] contact_info = request.POST['contact_info'] req = Request(content=content, contact_info=contact_info) req.save() return HttpResponseRedirect('/services/' + lang) return render_to_response('client/services/index.html', {'data': data}, RequestContext(request))
def test_model_unicode_is_a_part_of_comment_body(self): comment = Comment( post=self.post, author=self.author, guest_name=self.guest_name, body=self.body) self.assertIn(comment.__unicode__()[:-3], self.body) self.assertLessEqual(len(comment.__unicode__()), 80)