def comment_save(request): if request.user.is_authenticated is True: if request.method == "POST": profile = Profile.objects.get(user=request.user) pk = request.POST.get("post_pk") post = Post.objects.get(pk=pk) content = request.POST.get('content') if bool(content) != False: comment = Comment(user=profile, post=post, comment=content) comment.save() print(post.body) print(pk, content) print(bool(content)) return redirect(request.META.get('HTTP_REFERER')) else: return redirect("/")
def test_comment_content_renders_on_posts_view(self): """Test comment comntent is in post request.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = this_user this_post.content = 'tornado fire crocodile' this_post.title = 'marc ben benny built this site' this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.comment = 'this comment' this_comment.save() response = self.client.post( '/posts/' + str(this_post.id), follow=True) self.assertContains(response, 'this comment')
def add(request): post_id = request.POST.get("post_id") text = request.POST.get("text") if text is None or post_id is None: return HttpResponse(status=400) try: post = Post.objects.get(pk=post_id) new_comment = Comment( author=request.user, post=post, text=text, ) new_comment.save() except ObjectDoesNotExist as e: return JsonResponse({'error': e}) return HttpResponse(status=200)
def import_archive(): with open("comments.json", "r") as read_file: data = json.load(read_file) with open("users.json", "r") as read_file: data1 = json.load(read_file) with open("posts.json", "r") as read_file: data2 = json.load(read_file) with open("address.json", "r") as read_file: data3 = json.load(read_file) for i in range(len(data['comments'])): comments = Comment() comments.body = data['comments'][i]["body"] comments.email = data['comments'][i]["email"] comments.postId = data['comments'][i]["postId"] comments.id = data['comments'][i]["id"] comments.name = data['comments'][i]["name"] comments.save() for i in range(len(data2['posts'])): posts = Post() posts.body = data2['posts'][i]["body"] posts.userId = data2['posts'][i]["userId"] posts.title = data2['posts'][i]["title"] posts.id = data2['posts'][i]["id"] posts.save() for i in range(len(data1['users'])): users = Profile() users.username = data1['users'][i]["username"] users.address = data1['address'][i]["id"] users.email = data1['users'][i]["email"] users.save() for post in data2['posts']: profile = Profile.objects.get(id=post['userId']) Comment.objects.create(id=comment['id'], name=comment['name'], email=comment['email'], body=comment['body'], post=post)
def comment_list(request): if request.method == 'GET': comments = Comment.objects.all() for comment in comments: comment.to_json() return JsonResponse(Comment.objects.first().to_json(), safe=False) elif request.method == 'POST': data = json.loads(request.body) comment = Comment( name=data['name'], created=data['created'], due_on=data['due_on'], owner=data['due_on'], mark=data['mark'], list_id=data['list_id'] ) comment.save() return JsonResponse(comment.to_json())
def PostDetail(request, slug): post = get_object_or_404(Post, slug=slug) form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = Comment(author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post) comment.save() comments = Comment.objects.filter(post=post) context = { "post": post, "comments": comments, "form": form, } return render(request, "post.html", context)
def comment(request, username=None, post_id=None): post = Post.objects.filter(Q(id=post_id)) user = Users.objects.filter(Q(username=username)) if not post.exists() or not user.exists(): return JsonResponse( {"error": "Cannot comment for unknown user or post"}, status=400) user = user.first() post = post.first() data = json.loads(request.body) for key in ['comment']: if data.get(key) is None: return JsonResponse({"error": "%s is required" % key}, status=400) comm = Comment(comment=data['comment'], user=user, post=post) comm.save() return JsonResponse({"result": comm.to_json(keys=['user', 'post'])})
def leave_a_comment(request): #TODO: validate post, and checking the email and other variables to have values. post_id = request.POST['post_id'] p = Post.objects.get(pk=post_id) full_name = request.POST['full_name'] email = request.POST['email'] score = request.POST['score'] text = request.POST['text'] now = datetime.now() cmnt = Comment(post=p, full_name=full_name, email=email, score=score, text=text, display=False, date=now) cmnt.save() return JsonResponse({'status': 'ok'}, encoder=JSONEncoder)
def create_comments( copies: int, post_id: int, author_id:int=1, body='auto gen from script', approved=False): print('attempting to create comments') for n in range(copies): print('Copy[{}];\t \ post_id[{}];\n\t \ author_id[{}];\n\t \ approved[{}];'.format(n, post_id, author_id, approved)) p = get_object_or_404(Post, id=post_id) c = Comment(post=p, author=author_id, body=body) if approved: c.approve()
def insert_comment(post, comment_dict): # get the author specified by the comment author = Author.objects.get(id=comment_dict["comment"]["author"]["id"]) if "published" in comment_dict["comment"].keys(): comment_datetime = make_aware( dateutil.parser.isoparse(comment_dict["comment"]["published"])) else: comment_datetime = datetime.utcnow() comment = Comment(id=comment_dict["comment"]["id"], comment=comment_dict["comment"]["comment"], published=comment_datetime, post=post, author=author, contentType=comment_dict["comment"]["contentType"]) comment.save() return comment
def get_post(request, slug): post = Post.objects.get(slug=slug) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = Comment(**form.cleaned_data) comment.commenter = request.user comment.post = post comment.save() messages.add_message(request, messages.INFO, 'Your comment was published.') comments = Comment.objects.filter(post=post) form = CommentForm() return render(request, 'posts/post.html', { 'form': form, 'comments': comments, 'post': post })
def post(self, request, postId): like_list = {} comment_list = {} likes_total = {} #added post = Post.objects.get(id=postId) text = request.POST["comment"] comment = Comment(author=self.request.user, post=post, text=text) comment.save() like_list[post.id] = Like.objects.filter(post=post) comment_list[post.id] = Comment.objects.filter(post=post) likes_total[post.id] = len(Like.objects.filter(post=post)) #added return render( request, 'posts/like.html', { 'like_list': like_list, 'comment_list': comment_list, 'likes_total': likes_total, 'post': post })
def post(self,request): data = json.loads(request.body) try: if data['comment_text'] and data['post_id']: if Post.objects.filter(id=data['post_id']).exists(): Comment( comment_text = data['comment_text'], post_id = data['post_id'], comment_user_id = request.user.id ).save() comment_list = [] comments = Comment.objects.filter(post_id=data['post_id']) for comment in comments: comment_list.append({'num':comment.id,'comment_text':comment.comment_text}) print(comment_list) return JsonResponse({'comments':comment_list}, status=200) return JsonResponse({'message':'INVALID_Post_id'}, status=401) except KeyError: return JsonResponse({'message': 'KEY_ERROR'}, status=400)
def test_comment_belongs_to_link(self): link = Link.objects.create(title='poop', url='http://google.com') comment = Comment(text='butt', link=link) comment.save() self.assertIn(comment, Comment.objects.filter(link=link))
def test_comment_model_returns_string(self): """Test the post model has string function.""" instance = Comment() instance.comment = 'comment' assert str(instance) == 'comment'
def _add_comments(self, instance, comments): for comment_data in comments: comment_author = comment_data.pop('author', None) comment_instance = Comment(**comment_data) self._set_author(comment_instance, comment_author) instance.comments.append(comment_instance)
def comment(request): try: if request.method == 'POST': try: # Get Object user = User.objects.get(pk=request.data['user_id']) post = Post.objects.get(pk=request.data['post_id']) # Create Comment Object comment = Comment(text=request.data['text'], user=user, post=post) # Create Message Object if user.id != post.user_id: message = Message( text=f"{user.first_name} Commented on your post.", post=post, send_by=user, message_to=User.objects.get(pk=post.user_id)) message.save() # Save Object comment.save() # Response return JsonResponse({ "statusCode": 201, "statusText": "Created", "message": "Comment Posted!", "error": False }) except ObjectDoesNotExist: return JsonResponse({ "statusCode": 404, "statusText": "Not Found", "message": "Post Or User Not Exist", "error": True }) elif request.method == 'PUT': try: comment = Comment.objects.get(pk=request.data['comment_id']) comment.text = request.data['text'] comment.save() return JsonResponse({ "statusCode": 200, "statusText": "Success", "message": "Success", "error": False }) except ObjectDoesNotExist: return JsonResponse({ "statusCode": 404, "statusText": "Not Found", "message": "Comment Not Exist", "error": True }) except: return JsonResponse({ "statusCode": 500, "statusText": "Internal Server", "message": "Internal Server", "error": True })
def create(self, validated_data): task = Comment(**validated_data) task.save() return task