def new_comment(request, use_akismet=True): if request.method == "POST": post_id = request.POST.get('post_id', None) the_post = None if post_id: try: the_post = Post.objects.get(id=post_id) except Post.DoesNotExist: return redirect('/') if the_post: comment_author = request.POST.get('author', None) comment_email = request.POST.get('email', None) comment_content = request.POST.get('content', None) comment = Comment(author=comment_author, email=comment_email, content=comment_content, post=the_post) comment.author_user_agent = get_user_agent(request) comment.author_ip = get_ip(request) if use_akismet: if akismet_says_okay(comment): comment.approved = True else: # mainly for testing purposes comment.approved = True comment.save() return redirect(the_post.get_absolute_url()) else: return redirect('/')
def comment(request, pid): #todo: check if post allows comments print('test') data = json.loads(request.body) p = Post.objects.get(pk=pid) comment = Comment(content=data['content'], author_name=data['author'], post=p, published=timezone.now()) comment.save() return HttpResponse(status=200)
def post(self, request, *args, **kwargs): comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = Comment(author=request.user, post=self.get_object(), text=comment_form.cleaned_data['comments']) comment.save() else: raise Exception return redirect(reverse('detail', args=[self.get_object().id]))
def test_comment_can_belong_to_other_comment(self): link = Link.objects.create(title='poop', url='http://google.com') top_level_comment = Comment(text='butt', link=link, parent=None) top_level_comment.save() second_level_comment = Comment(text='butt', link=link, parent=top_level_comment) second_level_comment.save() self.assertIn(top_level_comment, Comment.objects.filter(link=link, )) self.assertIn(second_level_comment, Comment.objects.filter(parent=top_level_comment))
class CommentTestCode(APITestCase): def setUp(self) -> None: self.user = User(username='******', password='******') self.user.set_password(self.user.password) self.user.save() self.posts = baker.make(Post, _quantity=3) self.post = Post(image='kekeke', text='222222', owner=self.user) self.post.save() self.comments = baker.make(Comment, _quantity=3) self.comment = Comment(text='7777', post=self.post, author=self.user) self.comment.save() self.queryset = Comment.objects.all() def test_comment_crate(self): user = self.user self.client.force_authenticate(user=user) post = self.post data = { "text": "tttttttt" } response = self.client.post(f'/posts/{post.pk}/comments/', data=data) print('tttttttt', response.data) # response = self.client.post(f'/comments/{self.comment.pk}/reply/', data=data) self.assertEqual(response.data['text'], data['text']) def test_comment_list(self): user = self.user self.client.force_authenticate(user=user) response = self.client.get(f'/posts/{self.post.pk}/comments/') self.assertEqual(response.status_code, status.HTTP_200_OK) for a, b in zip(response.data, self.queryset): self.assertEqual(a['text'], b.text) self.assertEqual(a['author'], b.author_id) def test_comment_destroy(self): user = self.user self.client.force_authenticate(user=user) response = self.client.delete(f'/posts/{self.post.pk}/comments/{self.comment.pk}/') print('ㅇㅇㅇㅇㅇㅇㅇ', response) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertFalse(response.data)
def test_post_comment_200(self): """Test post comment view returns status code 200.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() response = self.client.post('/posts/' + str(this_post.id)) self.assertTrue(response.status_code == 200)
def create_comments_and_likes(): faker = Faker() for _ in range(100): author_id = str(random.randint(1, 10)) post = str(random.randint(1, 40)) text = faker.texts(nb_texts=3, max_nb_chars=200, ext_word_list=None) comment = Comment(author_id=author_id, post_id=post, text=text) comment.save() post_like = Post.objects.get(id=str(random.randint(1, 40))) post_like.likes.add(str(random.randint(1, 10))) for _ in range(200): comment_like = Comment.objects.get(id=str(random.randint(1, 100))) comment_like.likes.add(str(random.randint(1, 10)))
def test_comment_when_not_logged_in(self): """Should return Forbidden Status Code.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() response = self.client.post( '/posts/' + str(this_post.id), follow=True, comment='yo') self.assertTrue(response.status_code == 403)
def post(self, request, *args, **kwargs): #this function will deal with POST actions comment_form = CommentForm(request.POST) if comment_form.is_valid(): print(request.user) print(self.get_object()) print(comment_form.cleaned_data) comment = Comment(author=request.user, post=self.get_object(), text=comment_form.cleaned_data['comment']) print("hello") comment.save() else: #bad error handling raise Exception return redirect(reverse('detail', args=[self.get_object().id]))
def ajax_form_comment_post(request, idpost): msg = {'success': 0, 'message': ''} if request.is_ajax(): p = Post.objects.get(pk=idpost) c = Comment(post=p, text=request.POST['comment'], date=datetime.now()) try: c.save() msg['success'] = 1 msg['message'] = 'Comentario Insertado' except: msg['success'] = 0 msg['message'] = 'Error al insertar el comentario' json = simplejson.dumps(msg) return HttpResponse(json, mimetype='application/json')
def ajax_form_comment_post(request,idpost): msg = {'success': 0, 'message': ''} if request.is_ajax(): p = Post.objects.get(pk=idpost) c = Comment( post = p, text=request.POST['comment'], date=datetime.now() ) try: c.save() msg['success'] = 1 msg['message'] = 'Comentario Insertado' except: msg['success'] = 0 msg['message'] = 'Error al insertar el comentario' json = simplejson.dumps(msg) return HttpResponse(json, mimetype='application/json')
def add_comment(request, post_id): session_id = request.session.get('_auth_user_id', -1) if(session_id == -1): return HttpResponse("Must login to view this page") username = User.objects.get(pk=session_id) csrf_request = {} csrf_request.update(csrf(request)) new_comment = Comment( post = get_object_or_404(Post, pk=post_id), text=request.POST['new_comment_text'], pub_date = timezone.now(), author = username, love = 0, hate = 0) new_comment.save() return HttpResponseRedirect(reverse('posts.views.view_comments', args=(post_id,)))
def post_comment(request, post_id): if not request.user.is_authenticated: return redirect('login') if request.method == "POST" and request.POST.get('comment') != '': post = get_object_or_404(Post, pk=post_id) myUser = CustomUser.objects.get(user=request.user) com = Comment() com.post = post com.user = myUser com.date_pub = datetime.datetime.now() com.text = request.POST.get('comment') com.save() return redirect('post_index')
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 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_length_render_on_profile(self): """Test comment length render on profile post.""" this_user = self.users[0] self.client.force_login(this_user) this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() response = self.client.get('/profile/') self.assertContains(response, 'Comments: (2)')
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 test_comment_can_belong_to_other_comment(self): link = Link.objects.create(title='poop',url='http://google.com') top_level_comment = Comment(text='butt',link=link,parent=None) top_level_comment.save() second_level_comment = Comment(text='butt',link=link,parent=top_level_comment) second_level_comment.save() self.assertIn( top_level_comment, Comment.objects.filter( link = link, ) ) self.assertIn( second_level_comment, Comment.objects.filter( parent = top_level_comment ) )
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 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 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 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 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 })
class ReplyTestCode(APITestCase): def setUp(self): self.user = User(username='******', password='******',) self.user.set_password(self.user.password) self.user.save() self.post = Post(image='kekeke', text='222222', owner=self.user) self.post.save() self.comment = Comment(text='7777', post=self.post, author=self.user) self.comment.save() def test_reply_create(self): self.client.force_authenticate(user=self.user) data = { # 'parent': self.comment.pk, # 'author': self.user.author_id, 'text': 'RRRRRRRR', } response = self.client.post(f'/comments/{self.comment.pk}/reply/', data=data)
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 detail(request, post_id): try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: raise Http404 #return render(request, 'posts/detail.html', {'post': post}) if request.POST: form = CommentForm(request.POST) if form.is_valid(): content = form.cleaned_data['content'] c = Comment(content=content, post_id=post_id, user_id=request.user.id) c.save() return HttpResponseRedirect(reverse('posts:detail', args=[post_id])) else: render(request, 'posts/detail.html', {'post': post, 'form': form}) else: form = CommentForm() form = CommentForm() return render(request, 'posts/detail.html', {'post': post, 'form': form})
def test_comment(self): comment = Comment() post = Post() user = User.objects.create_user('Testy McTest', '*****@*****.**', 'testpassword') user.save() group = Group() group.name = "Test Group" group.save() membership = Membership() membership.user = User.objects.get(id = user.id) membership.group = Group.objects.get(id = group.id) membership.save() post.author = Membership.objects.get(id = membership.id) post.message = "Testing321" post.save() comment.author = Membership.objects.get(id = membership.id) comment.message = "123Testing" comment.post = Post.objects.get(id = post.id) comment.save() test_comment = Comment.objects.get(id = post.id) self.assertEquals(test_comment, comment) self.assertEquals(test_comment.author, Membership.objects.get(id = membership.id)) self.assertEquals(test_comment.message, "123Testing") self.assertEquals(test_comment.post, Post.objects.get(id = post.id)) comment.delete() post.delete() membership.delete() group.delete() user.delete()
def test_comment_length_render_on_other_user_profile(self): """Test comment length render on profile post.""" this_user = self.users[0] this_post = Post() this_post.author = this_user this_post.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() this_comment = Comment() this_comment.by_user = this_user this_comment.on_post = this_post this_comment.save() self.client.force_login(self.users[1]) response = self.client.get( '/profile/' + str(this_user.username), follow=True) self.assertContains(response, 'Comments: (3)')
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 gab_response(request, conversation): #print >>sys.stderr, "output" if request.method == 'GET': return HttpResponseRedirect('/posts/') current_user = request.user current_profile = UserProfile.objects.get(user=current_user) text = request.POST['gab'] conv = Conversation.objects.get(pk=int(conversation)) try: alreadyadded = CanPost.objects.get(conversation=conv, user=current_user) if not alreadyadded.test: comment = Comment(conversation=conv, text=text, user=current_user, profileid=current_profile.userid) comment.save() if request.is_ajax(): data = {} data['profileid'] = current_profile.userid data['first_name'] = current_user.first_name data['last_name'] = current_user.last_name data['conversation'] = str(conv.pk) data['gab'] = text data['comment'] = "TRUE" return HttpResponse(simplejson.dumps(data), mimetype="application/json") except: pass comment = Comment(conversation=conv, text=text, user=current_user, profileid=current_profile.userid) comment.save() if request.is_ajax(): data = {} data['profileid'] = current_profile.userid data['first_name'] = current_user.first_name data['last_name'] = current_user.last_name data['conversation'] = str(conv.pk) data['gab'] = text data['comment'] = "TRUE" return HttpResponse(simplejson.dumps(data), mimetype="application/json") gab = Gab(conversation=conv, text=text, user=current_user, profileid=current_profile.userid) gab.save() tags = request.POST['tag1'] if tags != "": tagdict = parsetags(tags) for person, profile in tagdict.iteritems(): try: added = CanPost.objects.get(conversation=conv, user=profile.user) if not added.test: canPost = CanPost(conversation=conv, user=profile.user, test=True) canPost.save() gab = Gab(conversation=conv, text=" was added.", user=profile.user, profileid=profile.userid) gab.save() except: pass canPost = CanPost(conversation=conv, user=profile.user, test=True) canPost.save() gab = Gab(conversation=conv, text=" was added.", user=profile.user, profileid=profile.userid) gab.save() if request.is_ajax(): data = {} data['profileid'] = current_profile.userid data['first_name'] = current_user.first_name data['last_name'] = current_user.last_name data['conversation'] = str(conv.pk) data['gab'] = text return HttpResponse(simplejson.dumps(data), mimetype="application/json") return HttpResponseRedirect('/posts/')
def expand_post(request,post_id): if request.user.is_authenticated(): my_profile = Profile.objects.get(user=request.user) try: post = Post.objects.get(uuid=post_id) except: hosts = Host.objects.all() for host in hosts: if host.name == "Group3": try: post_json = host.get_postid(post_id)['posts'][0] visibility = post_json['visibility'] description = post_json['description'] date = timezone.make_aware(datetime.datetime.strptime(post_json['pubdate'], '%Y-%m-%d'), timezone.get_default_timezone()) title = post_json['title'] content = post_json['content'] content_type = post_json['content-type'] author_id = post_json['author']['id'] author_host = post_json['author']['host'] author_displayname = post_json['author']['displayname'] try: author_user = User(username=author_displayname+'@Group3', password="") author_user.save() author_profile = Profile(user=author_user,uuid=author_id, displayname=author_displayname,host=author_host) author_profile.save() except: author_profile = Profile.objects.get(uuid=author_id) post = Post(title=title,post_text=content,author=author_profile,date=date,privacy='1') comments = [] comment_form = [] return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile}) except: pass elif host.name == "Group7": try: post_json = host.get_postid(post_id)['posts'][0] print(post_json) #visibility = post_json['visibility'] description = post_json['description'] date = date = timezone.make_aware(datetime.datetime.strptime('2015-04-01', '%Y-%m-%d'), timezone.get_default_timezone()) title = post_json['title'] content = post_json['content'] content_type = post_json['content-type'] author_id = post_json['author']['id'] author_host = post_json['author']['host'] author_displayname = post_json['author']['displayname'] try: author_user = User(username=author_displayname+'@Group3', password="") author_user.save() author_profile = Profile(user=author_user,uuid=author_id, displayname=author_displayname,host=author_host) author_profile.save() except: author_profile = Profile.objects.get(uuid=author_id) post = Post(title=title,post_text=content,author=author_profile,date=date,privacy='1') comments = [] comment_form = [] return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile}) except: pass try: if post.content_type == 'text/x-markdown': post.post_text = markdown2.markdown(post.post_text) current_profile = Profile.objects.get(user_id=request.user.id) comments = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): body = comment_form.cleaned_data['body'] newComment = Comment(body=body, date=timezone.now(), author=current_profile, post_id=post) newComment.save() else: print comment_form.errors return redirect('/posts/'+post_id) else: comments = Comment.objects.filter(post_id=post).order_by('date') comment_form = CommentForm() return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile}) except: return HttpResponse("Post not found", status=404)
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 create(self, validated_data): task = Comment(**validated_data) task.save() return task
def post(request, post_year, post_month, post_title): # Try to find the post that corresponds to the title. possibilities = Post.objects.filter( publication_date__year = post_year ).filter( publication_date__month = post_month ).filter( title = post_title ) if len(possibilities) == 1: found_post = possibilities[0] else: raise Http404 # If this is hit by a POST, someone is making a comment. if request.method == 'POST': form = CommentForm(request.POST) # Check form validity. If not valid, we'll drop through and render the # page. if form.is_valid(): # Hooray, form is filled out ok! Create a new comment. body_text = form.cleaned_data['text'] comment_author = form.cleaned_data['name'] comment = Comment(text = body_text, author = comment_author, post = found_post) comment.save() # At this point, we're happy to drop through and render the page. return HttpResponseRedirect(request.path) else: # Return an empty form and render the page. form = CommentForm() # Get the information in the form we want. This should be considered # subject to change. # Begin with the post title and body. post_components = post_as_components(found_post.body) post_title = post_components[0] post_remainder = post_components[2] # Other ancillary stuff. post_url = get_post_url(found_post) page_title = BLOG_PRE_TITLE + post_title comments_enabled = found_post.enable_comments # Get all the comments associated with the post. Only bother with this if # the comments are enabled on the post. if comments_enabled: comments = Comment.objects.filter(post = found_post).order_by("date") else: comments = [] # Got to build up the relevant contexts. context = RequestContext(request, {'PAGE_TITLE': page_title, 'PAGE_DESCRIPTION': None, 'post_title': post_title, 'post_body': post_remainder, 'post_url': post_url, 'comments_enabled': comments_enabled, 'comments': comments, 'publication_date': found_post.publication_date, 'form': form}) t = loader.get_template('post.html') return HttpResponse(t.render(context))
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))