def create_comment(request, isbn): user = request.user try: reader = Reader.objects.get(account__username__exact=user.username) except: return HttpResponseRedirect('/reader/login') else: target = Book.objects.get(isbn__exact=isbn) comments = Comment.objects.filter(isbn=target) if request.POST: content = request.POST.get('content', None) rating = request.POST.get('rating', None) comment = Comment(user=reader, isbn=target, rating=rating, content=content) comment.save() return HttpResponseRedirect('/reader/personalinfo') return render_to_response('comment/createcomment.html', locals())
def create(self, validated_data): request = self.context['request'] user = get_user_for_request(request) content = validated_data.get('content') email = validated_data.get('email') time_posted = timezone.now() comment = Comment(content_object=self.context['model_obj'], content=content, user=user, parent=self.context['parent_comment'], email=email, posted=time_posted) if settings.COMMENT_ALLOW_ANONYMOUS and not user: process_anonymous_commenting(request, comment, api=True) else: comment.save() return comment
def add_fresh(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: 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') return HttpResponse(json.dumps(result), content_type='application/json')
def detail(request, cf_id): try: confession = Confession.objects.get(pk=cf_id) except Confession.DoesNotExist: return redirect('homeconfession') #NOT DONE YET comments = Comment.objects.filter(confession=confession) if request.method == 'GET': return render(request, 'confession/details.html', {'confession': confession, 'comments': comments}) elif request.method == 'POST': if request.POST['text']: newcomment = Comment() newcomment.text = request.POST['text'] newcomment.pub_date = timezone.datetime.now() newcomment.author = request.user newcomment.confession = Confession.objects.get(pk=cf_id) newcomment.save() return redirect('detailconfession', confession.pk) else: return render(request, 'confession/details.html', {'confession': confession, 'error': 'You can\'t leave a blank comment', 'comments': comments})
def create_comment(request, slug, content_type): """ [This view creates the comments by geting the content type that needs to be created under] Arguments: request {[ request objects ]} -- [The request sent from the client] slug {[ string ]} -- [Used to filter the model objects comments would relate to] content_type {[ string ]} -- [Checks the kind of model that would be related to the comment object] Returns: [Json] -- [It returns a json response] """ lesson = Lesson.objects.get(id=slug) comment = Comment(content_object=lesson, text=request.data["textbox_value"], user=request.user) comment.save() comment_serialized = CommentSerializer(comment) return Response(status=status.HTTP_200_OK, data=comment_serialized.data)
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 post(self, request, post_id): comment = Comment() # 实例化类 comment.post_id = post_id comment.parent_id = request.POST['parent_id'] comment.reply_id = request.POST['reply_id'] comment.nick = request.POST['nick'] comment.mail = request.POST['mail'] comment.content = request.POST['content'] ua = parse_user_agent(request.META.get('HTTP_USER_AGENT', '')) # 解析HTTP_USER_AGENT comment.browser = ua['browser'] comment.client = ua['client'] # 处理回复评论 if request.POST['reply_id'] != '0': comment.comment_type = 'reply' reply_comment = Comment.objects.filter( id=request.POST['reply_id']).first() if reply_comment: comment.to_nick = reply_comment.nick comment.to_mail = reply_comment.mail # 如果是回复评论,则发送邮件通知相关评论人 recipient_list = EMAIL_RECEIVE_LIST + [reply_comment.mail] else: recipient_list = None else: # 如果是新的评论内容,则只需要发送通知博客作者 recipient_list = EMAIL_RECEIVE_LIST comment.save() # 保存评论数据到数据库 redirect_url = request.POST['redirect_url'] + '#comment-{0}'.format( comment.id) if recipient_list: # 发送邮件 try: send_email(url=redirect_url, recipient_list=recipient_list, post_id=post_id) except BaseException as e: print('发送邮件错误: {}'.format(e)) return redirect(redirect_url) # 重定向到指定页面
def update_comment(request): 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 parent: comment.root = parent.root if parent.root else parent comment.parent = parent comment.reply_to = parent.user comment.save() data['status'] = 'SUCCESS' else: data['status'] = 'ERROR' # print(data) return JsonResponse(data)
def comment_create(request): parm = {} to_comment_id = int(request.POST.get("to_comment_id", 0)) print("to_comment_id", to_comment_id) parm["content"] = request.POST.get("content") parm["article_id"] = request.POST.get("article_id") parm["b_id"] = request.POST.get("b_id") parm["page_no"] = request.POST.get("page_no") ok = {"status": "ok", "msg": "发布成功"} err = {"status": "err", "msg": "发布失败"} # article_id =64 # content =request.POST["content"] article_id = parm["article_id"] content = parm["content"] article_id = int(article_id) article = Article.objects.get(id=article_id) name = request.user link = "http://%s/article/%s/%s/detail?page_no=%s" % ( request.get_host(), parm["b_id"], parm["article_id"], parm["page_no"]) form = CommentForm(request.POST) if to_comment_id != 0: to_comment = Comment.objects.get(id=to_comment_id) owner = to_comment.owner else: to_comment = None owner = article.owner if form.is_valid(): comment = Comment(article=article, owner=name, content=content, to_comment=to_comment, status=0) comment.save() message = Message(owner=owner, content=content, link=link, status=0) message.save() return HttpResponse(json.dumps(ok)) else: return HttpResponse(json.dumps(err))
def form_valid(self, form): 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=self.model_obj, content=comment_content, user=user, parent=self.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 comment(request, **kwargs): # 通过id查找 id = kwargs['id'] blog_ = Blog.objects.filter(id=id).first() # if request.method == 'POST': # 获取name=comment的text内容 comment = request.POST.get('comment') if comment: # 实例化数据模型 cmt = Comment() # 评论和blog绑定 cmt.blog = blog_ # 评论数自加 cmt.count += 1 cmt.text = comment cmt.save() # else: # 可以审核评论 # 重定向到该博客显示页面 return redirect('/blog/%s' % id)
def post(self, request): try: data = request.data comment = Comment() comment.title = data.get('title') comment.body = data.get('body') comment.rate = data.get('rate') comment.booked_room = BookRoom.objects.get( pk=data['booked_room_id']) comment.save() return JsonResponse(status=status.HTTP_201_CREATED, message='create successful') except User.DoesNotExist: return JsonResponse(status=status.HTTP_404_NOT_FOUND, message="wrong id - user not found") except BookRoom.DoesNotExist: return JsonResponse(status=status.HTTP_404_NOT_FOUND, message="wrong id - booked_room not found") except IntegrityError: return JsonResponse( status=status.HTTP_400_BAD_REQUEST, message='for a booked_room you can add one comment')
def post(): '''写评论''' uid = session['uid'] wid = int(request.form.get('wid')) cid = int(request.form.get('cid', 0)) content = request.form.get('content', '').strip() created = datetime.datetime.now() if not content: return render_template(f'/weibo/show?wid={wid}&error=评论内容不为空') cmt = Comment(uid=uid, wid=wid, cid=cid, content=content, created=created) db.session.add(cmt) try: db.session.commit() except Exception as e: print(e) db.session.rollback() return redirect(f'/weibo/show?wid={wid}&error=评论失败') else: return redirect(f'/weibo/show?wid={wid}')
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'] data['content_type'] = ContentType.objects.get_for_model(comment).model 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() #发送邮件通知 comment.send_email() #返回数据 data['status'] = 'SUCCESS' data['username'] = comment.user.get_nickname_or_username() data['comment_time'] = comment.comment_time.timestamp() data['text'] = comment.text if not parent is None: data['reply_to'] = comment.reply_to.get_nickname_or_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 update_comment(request): comment_form = CommentForm(request.POST, user=request.user) data = {} if comment_form.is_valid(): # 检查文本框输入的数据是否有效 # 检查数据,保存数据,实例化一个comment对象 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() #发送邮件通知 comment.send_email() data['username'] = request.user.get_nickname_or_username() data['comment_time'] = comment.content_time.timestamp( ) #从格林威治时间1970/1/1/00时00分//00秒开始算 data['text'] = comment.text data['status'] = 'Success' if not parent is None: data['reply_to'] = comment.reply_to.get_nickname_or_username() else: data['reply_to'] = '' data['pk'] = comment.pk data['root_pk'] = comment.root.pk if not comment.root is None else '' else: data['status'] = 'Error' data['message'] = list(comment_form.errors.values())[0][0] # return render(request, 'error.html', {'message': comment_form.errors, 'redirect_to': referer}) return JsonResponse(data)
def post(self, request, *args, **kwargs): target_id = request.POST.get('post_id') target = Post.objects.filter(id=target_id)[0] content = request.POST.get('content') # content=mistune.markdown(raw_content) nickname = request.user.username comment = Comment() success = True msg = '' if nickname: comment.nickname = nickname else: msg = "必须登陆才能评论!" success = False if success: comment.content = content comment.target = target comment.save() return JsonResponse(data={'success': success, 'msg': msg})
def update_comment(request): 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'] comment.save() data = { 'status': 'SUCCESS', 'username': comment.user.username, 'comment_time': comment.comment_time.strftime('%Y-%m-%d %H:%M:%S'), 'text': comment.text, } else: data = { 'status': 'ERROR', 'message': list(comment_form.errors.values())[0][0] } return JsonResponse(data)
def post(self, request, comment_id): try: comment = Comment.objects.get(id=comment_id) except: return HttpResponse404Error( "You don\'t have permission to comment on this poll") poll = comment.get_poll meeting = poll.meeting text = request.data.get('text') owner = request.user if not MeetingParticipant.objects.filter(participant=owner, meeting=meeting): return HttpResponse404Error( "You don\'t have permission to comment on this poll") reply = Comment(owner=owner, poll=None, text=text, parent=comment, level=comment.level + 1) reply.save() reply_json = serializers.serialize('json', [reply]) return HttpResponse(reply_json, content_type='application/json')
def update_comment(request): #如果用户未登陆,则不允许评论 if not request.user.is_authenticated: return render(request, 'error.html', {'message': '用户未登陆'}) text = request.POST.get('text', '').strip() object_id = int(request.POST.get('object_id', '')) #如果评论内容为空,则不允许评论 if text == '': return render(request, 'error.html', {'message': '评论内容为空'}) blog = Blog() blogtype = ContentType.objects.get_for_model(blog) comment = Comment() comment.user, comment.text = request.user, text comment.content_type, comment.object_id = blogtype, object_id comment.save() #返回数据 data = {} data['username'] = comment.user.username data['comment_time'] = comment.comment_time.strftime('%Y-%m-%d %H:%M:%S') data['text'] = comment.text return JsonResponse(data)
def update_comment(request): referer = request.META.get('HTTP_REFERER', reverse('home')) comment_form = CommentForm(request.POST, user=request.user) data = dict() 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 if parent: data['reply_to'] = comment.reply_to.get_nickname_or_username() else: data['reply_to'] = '' data['id'] = comment.id data['root_id'] = comment.root.id if comment.root else '' else: # return render(request, 'error.html', {'message': comment_form.errors, 'referer': referer}) data['status'] = 'ERROR' data['message'] = list(comment_form.errors.values())[0][0] return JsonResponse(data)
def create(): req_data = request.get_json() data, error = comment_schema.load(req_data) if error: return custom_response(error, 400) # Create and save comment comment = Comment(contents=data['contents']) comment.save() # Connect owner owner_id = g.user.get('uid') owner = User.get(owner_id) comment.owner.connect(owner) article_external_id = data['article_external_id'] article = Article.get_by_external_id(article_external_id) if not article: article = Article(external_id=article_external_id) article.save() comment.article.connect(article) data = comment_schema.dump(comment).data return custom_response(data, 201)
def update_comment(request): '''referer = request.META.get('HTTP_REFERER', reverse('home')) user = request.user if not user.is_authenticated: return render(request, 'error.html', {'message': '用户未登录', 'redirect_to': referer}) text = request.POST.get('text', '').strip() if text == '': return render(request, 'error.html', {'message': '评论内容为空', 'redirect_to': referer}) 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(pk=object_id) except Exception as e: return render(request, 'error.html', {'message': '评论对象不存在', 'redirect_to': referer}) comment = Comment() comment.user = user comment.text = text comment.content_object = model_obj comment.save() return redirect(referer)''' referer = request.META.get('HTTP_REFERER', reverse('home')) # if not request.user.is_authenticated: # return render(request, 'error.html', {'message': '用户未登录', 'redirect_to': referer}) 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() # 发送邮件通知 comment.send_email() # 返回数据 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['content_type'] = ContentType.objects.get_for_model(comment).model if not parent is None: data['reply_to'] = comment.reply_to.get_nickname_or_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 comment_add(request, pk): if request.method == 'POST': now = datetime.datetime.now() year = now.year month = now.month day = now.day hour = now.hour minute = now.minute if len(str(month)) == 1: month = '0' + str(month) if len(str(day)) == 1: day = '0' + str(day) if len(str(hour)) == 1: hour = '0' + str(hour) if len(str(minute)) == 1: minute = '0' + str(minute) today = str(day) + '/' + str(month) + '/' + str(year) time = str(hour) + 'H' + str(minute) content = request.POST.get('msg') if request.user.is_authenticated: manager = Manager.objects.get() b = Comment(name=manager.name, email=manager.email, content=content, news_id=pk, date=today, time=time) b.save() else: newsname1 = News.objects.get(pk=pk).name name = request.POST.get('name') email = request.POST.get('email') if name == "": messages.error(request, "Vous devez saisir un nom d'utilisateur") return redirect('news_detail', word=newsname1) if len(name) < 3: messages.error(request, "Le nom doit comporter au moins 3 caractères") return redirect('news_detail', word=newsname1) if email == "": messages.error(request, "Vous devez saisir une adresse mail") return redirect('news_detail', word=newsname1) try: validate_email(request.POST.get("email")) except ValidationError: messages.error(request, 'Entrez une adresse mail valide') return redirect('news_detail', word=newsname1) if content == "": messages.error(request, "Vous devez saisir un commentaire") return redirect('news_detail', word=newsname1) if len(content) < 10: messages.error( request, "Le commentaire doit comporter au moins 10 caractères") return redirect('news_detail', word=newsname1) b = Comment(name=name, email=email, content=content, news_id=pk, date=today, time=time) b.save() newsname = News.objects.get(pk=pk).name messages.success(request, "Votre commentaire a été soumis avec succès") return redirect('news_detail', word=newsname)
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 # send email section current_site = get_current_site(self.request) article = self.comment.content_object author_email = article.author.email user_email = self.comment.user.email subject_email = '' messages_email = '' if author_email == user_email: author_email = False user_email = False parent_email = False if self.comment.parent: parent_email = self.comment.parent.user.email if parent_email in [author_email, user_email]: parent_email = False if author_email: subject_email = "دیدگاه جدید" messages_email = "دیدگاه جدیدی برای مقاله «{}» که شما نوینده آن هستید، ارسال شده:\n{}{}".format( article, current_site, reverse('blog:detail', kwargs={'slug': article.slug})) send_email.delay(subject_email, messages_email, author_email) if user_email: subject_email = "دیدگاه دریافت شد" messages_email = "دیدگاه شما دریافت شد و به زودی به آن پاسخ می دهیم." send_email.delay(subject_email, messages_email, user_email) if parent_email: subject_email = "پاسخ به دیدگاه شما" messages_email = "پاسخی به دیدگاه شما در مقاله «{}» ثبت شده است. برای مشاهده بر روی لینک زیر کلیک کنید:\n{}{}".format( article, current_site, reverse('blog:detail', kwargs={'slug': article.slug})) send_email.delay(subject_email, messages_email, parent_email) return self.render_to_response(self.get_context_data())
def update_comment(request): """# 发送此请求的网站 referer = request.META.get('HTTP_REFERER', reverse('home')) # 数据检查 if not request.user.is_authenticated: return render(request, 'error.html', {'message': '用户未登录', 'redirect_to': referer}) text = request.POST.get('text', '').strip() if text == '': return render(request, 'error.html', {'message': '评论内容为空', 'redirect_to': referer}) 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(pk=object_id) except Exception as e: return render(request, 'error.html', {'message': '评论对象不存在', 'redirect_to': referer}) # 检查通过,保存数据 comment = Comment() comment.user = request.user comment.text = text comment.content_object = model_obj comment.save() return redirect(referer)""" # 发送此请求的网站 referer = request.META.get('HTTP_REFERER', reverse('home')) comment_form = CommentForm(request.POST, user=request.user) if comment_form.is_valid(): # 检查通过,保存数据 comment = Comment() comment.user = comment_form.cleaned_data.get('user') comment.text = comment_form.cleaned_data.get('text') comment.content_object = comment_form.cleaned_data.get( 'content_object') parent = comment_form.cleaned_data.get('parent') if parent is not None: comment.parent = parent comment.root = parent.root if parent.parent is not None else parent comment.reply_to = parent.user comment.save() # 返回数据 data = { 'status': 'success', 'username': comment.user.get_nickname_or_username(), 'comment_time': comment.comment_time.strftime('%Y-%m-%d %H:%M:%S'), 'text': comment.text, 'content_type': ContentType.objects.get_for_model(comment).model, 'reply_to': comment.reply_to.get_nickname_or_username() if parent is not None else '', 'pk': comment.pk, 'root_pk': comment.root.pk if comment.root is not None else '' } # return redirect(referer) else: # return render(request, 'error.html', {'message': comment_form.errors, 'redirect_to': referer}) data = { 'status': 'error', 'message': list(comment_form.errors.values())[0][0] } return JsonResponse(data)
def post(self, request): data = json.loads(request.body) Comment(email=request.user, comment=data['comment']).save() return JsonResponse({'message': 'SUCCESS'}, status=200)
def comment(post, commenting_user): comment = Comment(post=post, author=commenting_user, content='comment1') comment.save() return comment
def commment(request): username = request.session.get('username', default=None) if username: user = User.objects.get(username=username) if request.method == "POST": if request.POST.get('comment_type'): text_form = comment_form(request.POST) comment = Comment() if text_form.is_valid(): comment.comment_text = text_form.cleaned_data[ 'comment_text'] parent_comment_id = request.POST['comment_id'] comment.comment_type = request.POST['comment_type'] comment.comment_img = request.FILES.get('comment_img') comment.comment_user = user parent_comment = Comment.objects.filter(pk=parent_comment_id) if parent_comment: comment.parent_comment = parent_comment[0] comment.root_comment = parent_comment[ 0].root_comment if not parent_comment[ 0].root_comment is None else parent_comment[0] comment.reply_user = parent_comment[0].comment_user else: comment.parent_comment = None comment.root_comment = None question_id = request.POST['question_id'] comment.comment_question = Question.objects.get( pk=question_id) comment.reply_user = Question.objects.get( pk=question_id).user user.integral += 3 comment.save() user.save() data = { 'comment_text': comment.comment_text, 'comment_date': comment.comment_time, 'comment_id': comment.pk } try: data['nickname'] = comment.comment_user.userinfo.all( )[0].nickname except: data['nickname'] = comment.comment_user.username return JsonResponse(data) else: comment_id = request.POST['comment_id'] question_id = request.POST['question'] comment = Comment.objects.get(pk=comment_id) question = Question.objects.get(pk=question_id) if question.user == user: admire_status = request.POST['admire'] admire_record = Admire_record() admire_record.admire_comment = comment admire_record.question = question admire_record.user = user admire_record.admire_user = comment.comment_user if admire_status == "yes": admire_record.is_admired = 1 user.integral += question.reward_integral // 3 + 5 data = {'admire_status': 'is_admired'} else: admire_record.is_admired = 0 data = {'admire_status': 'not_admired'} user.save() admire_record.save() return JsonResponse(data) else: user = User.objects.get(username=username) question_id = request.GET.get("question_id") question = Question.objects.get(pk=question_id) comments = Comment.objects.filter(comment_question=question, parent_comment=None) all_comments = Comment.objects.filter(comment_question=question) history_record = History_record() history_record.user = User.objects.get(username=username) history_record.viewed_question = question history_record.save() admire_record = Admire_record.objects.filter(user=user, question=question) context = {} context['all_comments'] = all_comments context['admire_records'] = admire_record context['comments'] = comments.order_by('comment_time') context['question'] = question context['comment_form'] = comment_form() if question.user == user: context['is_user'] = '******' try: context['your_headimg'] = Userinfo.objects.get( user=user).headimg.url except: context['your_headimg'] = '' return render(request, 'question_detail.html', context)
def comment(post, author): comment = Comment(author=author, post=post, content='comment') comment.save() return comment
def update_comment(request): # # 检查数据 # if not request.user.is_authenticated: # return render(request,'error.html',{'message':'用户未登陆','redirect_to':referer}) # text = request.POST.get('text', '').strip() # if text == '': # return render(request,'error.html',{'message':'评论内容为空','redirect_to':referer}) # 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(pk=object_id) # except Exception as e: # return render(request,'error.html',{'message':'评论对象不存在','redirect_to':referer}) # # 检查通过,保存数据 # comment = Comment() # comment.user = request.user # comment.text = text # comment.content_object = model_obj # comment.save() # # return redirect(referer) referer = request.META.get('HTTP_REFERER', reverse('article:index')) if not request.user.is_authenticated: return render(request, 'error.html', { 'message': '用户未登陆', 'redirect_to': referer }) 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.date() 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)