def mutate(root, info, id, content): message = '' user = info.context.user post = Post.objects.get(id=id) today = datetime.datetime.now().strftime('%d %B %Y') # Filter comments that belongs to user and are posted today comments_posted_today = Comment.objects.filter(user__username=user, posted=today) if content == '': raise GraphQLError('Content is not filled!') # If user has posted 20 or more comments if comments_posted_today.count() >= 20: message = 'You have reached your maximum comments per day! (20)' # Sucess else: # Create date when was the post posted posted = datetime.datetime.now().strftime('%d %B %Y') comment = Comment(post=post, user=user, content=content, posted=posted) comment.save() message = 'Success' return CommentPost(message=message)
def post(self, request, *args, **kwargs): comment = request.data.get('comment', None) post_id = request.data.get('blogId', None) if comment is None: return Response({'message': 'Invalid comment received.'}, status=HTTP_404_NOT_FOUND) if post_id is None: return Response({'message': 'This blog does not exist.'}, status=HTTP_404_NOT_FOUND) try: post = Post.objects.get(id=post_id) except ObjectDoesNotExist: raise Http404('This blog does not exist.') if request.user.is_authenticated: new_comment = Comment(user=request.user, content=comment, post=post) new_comment.save() post.comments.add(new_comment) post.save() return Response({'message': 'Successfully submitted a comment.'}, status=HTTP_201_CREATED) else: return Response({'message': 'You must login first.'}, status=HTTP_401_UNAUTHORIZED)
def post(self, request, *args, **kwargs): new_comment = Comment(comment=request.POST.get('comment'), user=self.request.user, post=self.get_object()) if new_comment.comment.__len__() > 0: new_comment.save() return self.get(self, request, *args, **kwargs)
def post_page(request, id): mypost = Post.objects.get(pk=id) if request.method == "POST": form = AddComment(request.POST) if form.is_valid(): poster = request.user content = request.POST['content'] upvotes = 1 root = None post = Post.objects.get(pk=id) new_comment = Comment(poster=poster, content=content, upvotes=upvotes, root=root, post=post) new_comment.save() return render( request, "posts/post_page.html", { "post": mypost, "form": AddComment(), "comments": Comment.objects.all() }) return render(request, "posts/post_page.html", { "post": mypost, "form": AddComment(), "comments": Comment.objects.all() })
def post(self, request, *args, **kwargs): com = request.POST.get('comment') user_id = request.POST.get('user_id') post_id = request.POST.get('post_id') user = User.objects.get(id=user_id) post = Post.objects.get(id=post_id) comt = Comment(comment=com, comment_user=user, comment_post=post) comt.save() return redirect(reverse("post", kwargs={'pk': self.kwargs['pk']}))
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 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 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['comment']) comment.save() else: raise Exception return redirect(reverse('detail', args=[self.get_object().id]))
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 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 create_comment_view(request, post_id): if request.method == 'POST': post = Post.objects.get(pk=post_id) if request.user.is_authenticated(): if post: comment = Comment() comment.body = request.POST['body'] comment.pub_date = timezone.datetime.now() comment.post = post comment.author = request.user comment.save() return JsonResponse( { "status": "success", "message": "answer created", "comment_id": comment.pk }, status=201) else: return JsonResponse( { "status": "failure", "message": "post not exist" }, status=404) else: return JsonResponse( { "status": "failure", "message": "user need to login" }, status=403) else: return render(request, 'posts/create-commentd.html', {'post_id': post_id})
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 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 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 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 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 p_read(request, post_id): post = get_object_or_404(Post, pk=post_id) session = request.session['user'] if request.method == 'POST': # POST 방식으로 호출 될 때 user_id = request.session.get('user') user = User.objects.get(username=user_id) comment = Comment(post=post, author=user_id) comment_form = CommentForm(request.POST, instance=comment) if comment_form.is_valid(): comment_form.save() return redirect(f'/posts/{post_id}/read') else: # GET 방식으로 호출 될 때 comment_form = CommentForm() context = { 'post': post, 'comment_form': comment_form, 'session': session } return render(request, 'read.html', context)
def import_data(): # Initial Imports from django.contrib.auth.models import User # Processing model: posts.models.Post from posts.models import Post posts_post_1 = Post() posts_post_1.author = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_post_1.link = 'https://stackoverflow.com/questions/3330435/is-there-an-sqlite-equivalent-to-mysqls-describe-table' posts_post_1.title = 'Initial Data' posts_post_1.description = 'Cool Description' posts_post_1 = importer.save_or_locate(posts_post_1) posts_post_2 = Post() posts_post_2.author = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_post_2.link = 'https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html' posts_post_2.title = 'Reset Generator' posts_post_2.description = 'https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html' posts_post_2 = importer.save_or_locate(posts_post_2) # Processing model: posts.models.Vote from posts.models import Vote posts_vote_1 = Vote() posts_vote_1.voter = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_vote_1.post = posts_post_1 posts_vote_1.liked = True posts_vote_1 = importer.save_or_locate(posts_vote_1) posts_vote_2 = Vote() posts_vote_2.voter = importer.locate_object(User, "id", User, "id", 2, {'id': 2, 'password': '******', 'last_login': None, 'is_superuser': False, 'username': '******', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 35, 12, 746625, tzinfo=<UTC>)} ) posts_vote_2.post = posts_post_1 posts_vote_2.liked = True posts_vote_2 = importer.save_or_locate(posts_vote_2) # Processing model: posts.models.Comment from posts.models import Comment posts_comment_1 = Comment() posts_comment_1.description = 'My Cool Comment on Post 1 yeh.' posts_comment_1.author = importer.locate_object(User, "id", User, "id", 1, {'id': 1, 'password': '******', 'last_login': datetime.datetime(2018, 11, 27, 6, 31, 56, 449061, tzinfo=<UTC>), 'is_superuser': True, 'username': '******', 'first_name': '', 'last_name': '', 'email': '*****@*****.**', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2018, 11, 27, 6, 31, 35, 527568, tzinfo=<UTC>)} ) posts_comment_1.post = posts_post_1 posts_comment_1 = importer.save_or_locate(posts_comment_1)
def test_comment_score_is_upvotes_minus_downvotes(self): link = Link.objects.create(title='butt', url='http://poop.bike') comment = Comment(text='fart', parent=None, link=link, upvotes=5, downvotes=3) self.assertEqual(comment.score, 2)
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 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 delete_comment(post_id, comment_id): comment = Comment.get_by_id(comment_id) if comment is None: flash('Incorrect comment!') return redirect(url_for('posts.view_post', post_id=post_id)) db_session.delete(comment) db_session.commit() return redirect(url_for('posts.view_post', post_id=post_id))
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_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 setUp(self, github_api_call): """Set up for backend test runner.""" self.users = [UserFactory.create() for i in range(5)] self.posts = [Post() for i in range(5)] for i in range(len(self.posts)): self.posts[i].author = self.users[i] self.posts[i].title = factory.Sequence( lambda n: "Post{}".format(n)) self.posts[i].save() self.comments = [Comment() for i in range(5)]
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 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 commentreply(request, commentid): context = {} if request.method == 'POST': posts = request.POST.get("postvalue", "") commenttext = request.POST.get("commenttext", "") currpost = Post.objects.get(pk=posts) if commentid != 0: parentcomment = Comment.objects.get(pk=commentid) level = parentcomment.level + 1 else: parentcomment = None level = 0 user = request.user c = Comment(author=user, post=currpost, parentcomment=parentcomment, text=commenttext, level=level) c.save() if commentid != 0: c.level = 1 else: c.level = 0 context['c'] = c else: pass return render(request, 'posts/comment.html', context)
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 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 add_comment_to_post(request, post_id): post = get_object_or_404(Post, pk=post_id) if request.method == "POST": comment = Comment(post=post) comment_form = CommentForm(request.POST, instance=comment) if comment_form.is_valid(): comment_form.save() path = '/posts/{}/'.format(post_id) return redirect(path) else: comment_form = CommentForm() return render(request, 'add_comment_to_post.html', {'comment_form':comment_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_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 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 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))