def send_comment(post_id, comment_user, comment_text, comment_image): usr = User.objects.get(id=comment_user) ps = Post.objects.get(id=post_id) import uuid nameFile = str(uuid.uuid4())[:12] imgstr = re.search(r'base64,(.*)', comment_image).group(1) # path = default_storage.save('%s.png' % nameFile, ContentFile(imgstr)) img_file = open("media/%s.png" % nameFile, 'wb') img_file.write(base64.b64decode(imgstr)) img_file.close() post = Comment() post.comment_text = comment_text post.comment_image = nameFile post.post_id = ps post.comment_user = usr post.save() user_post = str(usr.username) r = redis.StrictRedis() if user_post: r.publish( "".join(['post_', post_id, '_comments']), json.dumps({ "user_post": user_post, "title": comment_text, }))
def detail(request, pk): p = Post.objects.get(pk=pk) comments = Comment.objects.filter(post_id=pk) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... comment = form.cleaned_data['comment'] c = Comment(post_id=pk, comment=comment, user=request.user) c.save() # redirect to a new URL: return HttpResponseRedirect( reverse('myapp:detail', kwargs={'pk': pk})) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() return render(request, 'detail.html', { 'form': form, 'p': p, 'comments': comments })
def comment(request): errors = {} valid, data = validate_session(request) if not valid: return data if request.method == 'POST': try: body = json.loads(request.body) comment_id = 'c_' + str(uuid.uuid4()) dweet_id = body['dweet_id'] comment_data = body['comment'] created_time = str(datetime.datetime.now()) account_id = data comment = Comment(comment_id=comment_id, dweet_id=dweet_id, comment_data=comment_data, created_time=created_time, account_id=account_id) comment.save() return getResonse({"status": "success"}, 201) except KeyError as ke: print ke return getResonse({ "status": "failed", "data_missing": ke.message }, 422) except Exception as e: print e return getResonse({"status": "failed"}, 500) else: return getResonse({"status": "failed"}, 405)
def add_comment(request): if request.method == 'POST': try: payload = json.loads(request.body) comment_id = uuid.uuid4().hex[:10] post_id = payload['post_id'] body = payload['body'] posted_by = payload['posted_by'] parent_id = payload['parent_id'] posted_date = int(time.time()) post = get_object_or_404(Post, post_id=post_id) post.last_posted_by = posted_by post.last_posted_date = posted_date post.replies = F('replies') + 1 post.save() comment = Comment(comment_id, post_id, body, posted_by, posted_date, parent_id) comment.save() response = json.dumps([{ 'success': 'Comment added successfully!', 'commentid': comment_id }]) except: response = json.dumps([{'error': 'Comment could not be added!'}]) return HttpResponse(response, content_type='text/json') else: response = json.dumps([{'error': 'Comment could not be added!'}]) return HttpResponse(response, status='404', content_type='text/json')
def detail(request, pk): d = Post.objects.get(pk=pk) comments = Comment.objects.filter(post=d) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): comment = form.cleaned_data['comment'] # print(comment,pk) #save comment in Comment model that is in data base c = Comment(post=d, comment=comment, user=request.user) c.save() # process the data in form.cleaned_data as required # ... # redirect to a new URL: context = {'post': d, 'form': form, 'comments': comments} return render(request, 'detail.html', context) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() context = {'post': d, 'form': form, 'comments': comments} return render(request, 'detail.html', context)
def postComment(request): if request.method == 'POST': comments = request.POST.get("comment") user = request.user postSno = request.POST.get("postSno") post = Post.objects.get(sno=postSno) comments = Comment(comments=comments, user=user, post=post) comments.save() messages.success(request, "Your comment has been posted") return redirect(f"/blog/{post.slug}")
def add_comment(request, id): token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] payload = jwt_decode_handler(token) user_id = payload['user_id'] try: user = User.objects.get(pk=user_id) post = Post.objects.get(pk=id) comment = Comment(user=user, post=post, text=request.data['text']) comment.save() return Response('Success', status=status.HTTP_201_CREATED) except Exception: return Response('Error', status.HTTP_401_UNAUTHORIZED)
def home(request, articleType,url='/'): request.session.set_expiry(0) username = request.session.get('username', False) print(username) if not username: pass#username = '******' if request.method == "POST": comment=Comment() comment.username=request.session.get('username', False) if url == '/': blog_list = BlogsPost.objects.filter(artcileType=articleType) thisBlog = BlogsPost.objects.get(title=blog_list[0].title) comment.title=thisBlog.title comment.time=datetime.datetime.now() else: thisBlog = BlogsPost.objects.get(title=url) thisBlog.commentNum=thisBlog.commentNum+1; thisBlog.save(); comment.title=thisBlog.title comment.time=datetime.datetime.now() comment.userimg='/static/img/jslogo.jpg' comment.body=request.POST.get('content',False) comment.save() if url=='/': comments=Comment.objects.filter(title=blog_list[0].title) return HttpResponseRedirect('/', {'posts': blog_list, 'post': blog_list[0], 'username': username,'comments':comments}) else: blog_list = BlogsPost.objects.filter(artcileType=articleType) thisBlog = BlogsPost.objects.get(title=url) comments=Comment.objects.filter(title=thisBlog.title) return HttpResponseRedirect(url, {'post': thisBlog, 'posts': blog_list, 'username': username,'comments':comments}) else: blog_list = BlogsPost.objects.filter(artcileType=articleType) for blog in blog_list: blog.url = "/article/" +blog.artcileType + '/'+blog.title if url == '/': comments=Comment.objects.filter(title=blog_list[0].title) #print(blog_list[0].body) return render_to_response('home.html', {'posts': blog_list, 'post': blog_list[0], 'username': username,'comments':comments}) else: thisBlog = BlogsPost.objects.get(title=url) thisBlog.readNum =thisBlog.readNum+1 thisBlog.save() comments=Comment.objects.filter(title=thisBlog.title) return render_to_response('home.html', {'post': thisBlog, 'posts': blog_list, 'username': username,'comments':comments})
def add_stock_comment(request): """This function adds comments to Comments table for a specific stock . **Template:** :template:'myapp/templates/signle_stock.html' """ if request.method == 'POST': if request.POST.get('name') and request.POST.get('content'): comment = Comment() comment.author = request.POST.get('name') comment.text = request.POST.get('content') comment.stock_id = request.POST.get('stock_symbol') symbol = request.POST.get('stock_symbol') comment.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def main_page(request, country_code="global"): file = open('spotify_countries.json') countries = json.load(file) comments = Comment.objects.all().order_by("date") if country_code == None: country_code = "global" top_ten = get_top_ten(country_code) login_form = AuthenticationForm(request.POST) if request.method == 'GET' and request.is_ajax(): data = dict(request.GET) first = next(iter(data.keys())) print(first) if first == 'Song': song = data['Song'][0] artist = data['Artist'][0] #call get_lyrics scraper lyrics = get_lyrics(song, artist) return HttpResponse(lyrics, content_type="text") if request.method == 'POST' and request.is_ajax(): json_response = json.loads(request.body) if json_response["messageType"] == "comment": comment = json_response["comment"] user = json_response["user"] new_comment = Comment(user=user, comment=comment) new_comment.save() response = "< " + user + " >: " + comment return HttpResponse(response) return render( request, 'base.html', { 'login_form': login_form, 'top_tracks': top_ten, 'countries': countries, 'comments': comments })
def comment_edit(request, song_id, comment_id=None): """コメントの編集""" song = get_object_or_404(Song, pk=song_id) # 親の曲を読む # comment_idが指定されている(修正時) if comment_id: comment = get_object_or_404(Comment, pk=comment_id) # comment_idが指定されていない(追加時) else: comment = Comment() if request.method == 'POST': # POSTされたrequestデータからフォームを作成 form = CommentForm(request.POST, instance=comment) if form.is_valid(): comment = form.save(commit=False) comment.song = song comment.save() return redirect('myapp:comment_list', song_id=song_id) else: # GETの時 form = CommentForm(instance=comment) return render(request, 'myapp/comment_edit.html', dict(form=form, song_id=song_id, comment_id=comment_id))
def commentview(request,id): x=request.POST['comment'] s=Comment(message=x,MessageId_id=id) s.save() return HttpResponseRedirect('/myapp/article/%s'% id)
def index(request): if request.method == "GET": vCourse_id = request.GET["course_id"] author_id = request.GET["user_id"] author = User.objects.get(id=author_id) cl = Curriculumn.objects(id=vCourse_id) has_curriculum = False try: is_mentor = request.session["is_mentor"] except Exception as e: is_mentor = False user = User.objects.get(username=str(request.user)) student = Student.objects(user=user.id) status = "1" if len(cl): has_curriculum = True clTaken = 0 clLike = 0 mtTaken = 0 mtLike = 0 actTaken = 0 actLike = 0 mtTotal = 0 actTotal = 0 is_joined = False if len(student): progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student[0].id) if len(progress) > 0: is_joined = True lscl = [] lscl = cl[0] for i in lscl.__getattribute__("material"): i.note = "0" try: is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id) if len(is_like): i.note = "1" i.__getattribute__("statistic").currentLikeNumber -= 1 except Exception as e: print(e) avatar = "" try: avatar = request.session["avatar"] except Exception as e: request.session["avatar"] = "" print(e) context = { "cl": lscl, "is_joined": is_joined, "user_id": request.user, "course_id": vCourse_id, "author_id": author_id, "author": author.username, "is_mentor": is_mentor, "clTaken": clTaken, "clLike": clLike, "mtTaken": mtTaken, "mtLike": mtLike, "actTaken": actTaken, "actLike": actLike, "mtTotal": mtTotal, "actTotal": actTotal, "has_curriculum": has_curriculum, "avatar": avatar, } return render(request, "myapp/course-detail.html", context) elif request.method == "POST": if request.POST["posttype"] == "likeMaterial": user = User.objects.get(username=str(request.user)) print(request.POST["posttype"]) materialId = request.POST["materialId"] status = request.POST["status"] # like or dislike # update status=0 for recors last with status=1,user_id,material sdLast = StatisticDetail.objects(user=user.id, object_id=str(materialId), status="1").order_by( "published_date" )[:10] if len(sdLast): for sdUpdate in sdLast: sdUpdate.status = "0" sdUpdate.save() else: print("no update ") sdNew = StatisticDetail() sdNew.user = user sdNew.object_id = str(materialId) if status == "0": sdNew.status = "1" else: sdNew.status = "0" sdNew.save() # update or insert statistic stCurent = Statistic.objects(object_id=str(materialId)).order_by("create_date")[:1] stNew = Statistic() if len(stCurent) > 0: stNew = stCurent[0] if status == "1": stNew.currentLikeNumber -= 1 else: stNew.currentLikeNumber += 1 stNew.type = "1" stNew.save() else: if status == "0": stNew.currentLikeNumber = 1 else: stNew.currentLikeNumber = 0 stNew.object_id = str(materialId) stNew.type = "1" stNew.save() # update material mtCurrent = Material.objects.get(id=materialId) mtCurrent.statistic = stNew mtCurrent.note = "0" mtCurrent.save() return HttpResponse(json.dumps({"formdata": materialId}), content_type="application/json") elif request.POST["posttype"] == "frmJoincourse": curriculum_id = request.POST["curriculum_id"] user_id = request.POST["user_id"] print(curriculum_id) curriculum = Curriculumn.objects.get(id=curriculum_id) user = User.objects.get(username=str(request.user)) student = Student.objects(user=user.id) planstart = request.POST["planstart"] planend = request.POST["planend"] impression = request.POST["impression"] description = request.POST["description"] # Save CurriculumnStudyProgress csp = CurriculumnStudyProgress() if len(student): st = student[0] csp.student = st csp.curriculumn = curriculum csp.PlanStartDate = datetime.strptime(planstart, "%m/%d/%Y") csp.PlanEndDate = datetime.strptime(planend, "%m/%d/%Y") csp.impression = Impression.objects.get(showpiority=impression) csp.description = description csp.save() # UPDATE Curriculumn print(user.id) curri = Curriculumn() curri = Curriculumn.objects.get(id=curriculum_id) curri.joined_user.append(user) curri.save() # Save CurriculumnLog lisProgressType = ProgressType.objects().order_by("rate") progressType = lisProgressType[0] curriLog = CurriculumnLog() curriLog.curriculumn = curri curriLog.process = progressType curriLog.data = "[]" curriLog.user_id = user curriLog.save() # SHOW Record cl = Curriculumn.objects(id=curriculum_id) has_curriculum = False is_mentor = False mentor = Mentor.objects(user=user.id) if len(mentor): is_mentor = True if len(cl): has_curriculum = True print(has_curriculum) clTaken = 0 clLike = 0 mtTaken = 0 mtLike = 0 actTaken = 0 actLike = 0 mtTotal = 0 actTotal = 0 try: for c in cl: if c.statistic.currentTakenNumber: clTaken += c.statistic.currentTakenNumber if c.statistic.currentLikeNumber: clLike += c.statistic.currentLikeNumber for mt in c.material: if mt.statistic.currentTakenNumber: mtTaken += mt.statistic.currentTakenNumber if mt.statistic.currentLikeNumber: mtLike += mt.statistic.currentLikeNumber mtTotal += 1 for act in c.action: if act.statistic.currentTakenNumber: actTaken += act.statistic.currentTakenNumber if act.statistic.currentLikeNumber: actLike += act.statistic.currentLikeNumber actTotal += 1 except Exception as e: print(e) is_joined = False if len(student): progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student[0].id) if len(progress) > 0: is_joined = True context = { "cl": cl[0], "is_joined": is_joined, "user_id": request.user, "course_id": curriculum_id, "author": user.username, "is_mentor": is_mentor, "clTaken": clTaken, "clLike": clLike, "mtTaken": mtTaken, "mtLike": mtLike, "actTaken": actTaken, "actLike": actLike, "mtTotal": mtTotal, "actTotal": actTotal, "has_curriculum": has_curriculum, } return HttpResponseRedirect("course-detail?course_id=" + curriculum_id + "&user_id=" + user_id) elif request.POST["posttype"] == "deleteComment": try: comment_status = "0" comment_id = request.POST["hd_comment_id"] course_id = request.POST["hd_course_id"] author_id = request.POST["hd_author_course_id"] user_id = request.session["_auth_user_id"] cmt = Comment.objects.get(id=comment_id) cmt.status = comment_status cmt.save() status = "1" author = User.objects.get(id=author_id) cl = Curriculumn.objects(id=course_id) has_curriculum = False is_mentor = request.session["is_mentor"] user = User.objects.get(username=str(request.user)) student = Student.objects.get(user=user.id) clTaken = 0 clLike = 0 mtTaken = 0 mtLike = 0 actTaken = 0 actLike = 0 mtTotal = 0 actTotal = 0 try: for c in cl: if c.statistic.currentTakenNumber: c.statistic.currentTakenNumber = 10 clTaken += c.statistic.currentTakenNumber if c.statistic.currentLikeNumber: clLike += c.statistic.currentLikeNumber for mt in c.material: if mt.statistic.currentTakenNumber: mtTaken += mt.statistic.currentTakenNumber if mt.statistic.currentLikeNumber: mtLike += mt.statistic.currentLikeNumber mtTotal += 1 print(mt.name) for act in c.action: if act.statistic.currentTakenNumber: actTaken += act.statistic.currentTakenNumber if act.statistic.currentLikeNumber: actLike += act.statistic.currentLikeNumber actTotal += 1 except Exception as e: print(e) progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student.id) is_joined = False if len(progress) > 0: is_joined = True lscl = [] lscl = cl[0] for i in lscl.__getattribute__("material"): i.note = "0" try: is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id) if len(is_like): i.note = "1" i.__getattribute__("statistic").currentLikeNumber -= 1 except Exception as e: print(e) context = { "cl": lscl, "is_joined": is_joined, "user_id": request.user, "course_id": course_id, "author_id": author_id, "author": author.username, "is_mentor": is_mentor, "clTaken": clTaken, "clLike": clLike, "mtTaken": mtTaken, "mtLike": mtLike, "actTaken": actTaken, "actLike": actLike, "mtTotal": mtTotal, "actTotal": actTotal, "has_curriculum": has_curriculum, } except Exception as e: print(e) finally: return render(request, "myapp/course-detail.html", context) elif request.POST["posttype"] == "editComment": try: comment = request.POST["txtcommentName"] comment_id = request.POST["hd_comment_id"] course_id = request.POST["hd_course_id"] author_id = request.POST["hd_author_course_id"] user_id = request.session["_auth_user_id"] cmt = Comment.objects.get(id=comment_id) cmt.content = comment cmt.save() status = "1" author = User.objects.get(id=author_id) cl = Curriculumn.objects(id=course_id) has_curriculum = False is_mentor = request.session["is_mentor"] user = User.objects.get(username=str(request.user)) student = Student.objects.get(user=user.id) clTaken = 0 clLike = 0 mtTaken = 0 mtLike = 0 actTaken = 0 actLike = 0 mtTotal = 0 actTotal = 0 try: for c in cl: if c.statistic.currentTakenNumber: c.statistic.currentTakenNumber = 10 clTaken += c.statistic.currentTakenNumber if c.statistic.currentLikeNumber: clLike += c.statistic.currentLikeNumber for mt in c.material: if mt.statistic.currentTakenNumber: mtTaken += mt.statistic.currentTakenNumber if mt.statistic.currentLikeNumber: mtLike += mt.statistic.currentLikeNumber mtTotal += 1 print(mt.name) for act in c.action: if act.statistic.currentTakenNumber: actTaken += act.statistic.currentTakenNumber if act.statistic.currentLikeNumber: actLike += act.statistic.currentLikeNumber actTotal += 1 except Exception as e: print(e) progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student.id) is_joined = False if len(progress) > 0: is_joined = True lscl = [] lscl = cl[0] for i in lscl.__getattribute__("material"): i.note = "0" try: is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id) if len(is_like): i.note = "1" i.__getattribute__("statistic").currentLikeNumber -= 1 except Exception as e: print(e) context = { "cl": lscl, "is_joined": is_joined, "user_id": request.user, "course_id": course_id, "author_id": author_id, "author": author.username, "is_mentor": is_mentor, "clTaken": clTaken, "clLike": clLike, "mtTaken": mtTaken, "mtLike": mtLike, "actTaken": actTaken, "actLike": actLike, "mtTotal": mtTotal, "actTotal": actTotal, "has_curriculum": has_curriculum, } except Exception as e: print(e) finally: return render(request, "myapp/course-detail.html", context) else: comment = request.POST["txtComment"] course_id = request.POST["hd_course_id"] material_id = request.POST["hd_material_id"] user_id = request.session["_auth_user_id"] author_id = request.POST["hd_author_course_id"] ur = request.user cmt = Comment() cmt.user = request.user cmt.content = comment cmt.save() cl = Curriculumn.objects.get(id=course_id) mt = Material.objects.get(id=material_id) mt.comment.append(cmt) mt.save() cl.save() status = "1" print(author_id) author = User.objects.get(id=author_id) cl = Curriculumn.objects(id=course_id) has_curriculum = False is_mentor = request.session["is_mentor"] user = User.objects.get(username=str(request.user)) student = Student.objects.get(user=user.id) clTaken = 0 clLike = 0 mtTaken = 0 mtLike = 0 actTaken = 0 actLike = 0 mtTotal = 0 actTotal = 0 try: for c in cl: if c.statistic.currentTakenNumber: c.statistic.currentTakenNumber = 10 clTaken += c.statistic.currentTakenNumber if c.statistic.currentLikeNumber: clLike += c.statistic.currentLikeNumber for mt in c.material: if mt.statistic.currentTakenNumber: mtTaken += mt.statistic.currentTakenNumber if mt.statistic.currentLikeNumber: mtLike += mt.statistic.currentLikeNumber mtTotal += 1 print(mt.name) for act in c.action: if act.statistic.currentTakenNumber: actTaken += act.statistic.currentTakenNumber if act.statistic.currentLikeNumber: actLike += act.statistic.currentLikeNumber actTotal += 1 except Exception as e: print(e) progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student.id) is_joined = False if len(progress) > 0: is_joined = True lscl = [] lscl = cl[0] for i in lscl.__getattribute__("material"): i.note = "0" try: is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id) if len(is_like): i.note = "1" i.__getattribute__("statistic").currentLikeNumber -= 1 except Exception as e: print(e) context = { "cl": lscl, "is_joined": is_joined, "user_id": request.user, "course_id": course_id, "author_id": author_id, "author": author.username, "is_mentor": is_mentor, "clTaken": clTaken, "clLike": clLike, "mtTaken": mtTaken, "mtLike": mtLike, "actTaken": actTaken, "actLike": actLike, "mtTotal": mtTotal, "actTotal": actTotal, "has_curriculum": has_curriculum, } return render(request, "myapp/course-detail.html", context)