def render_post(request, post): # render "raw" newsletters if post.type == Post.TYPE_WEEKLY_DIGEST: return HttpResponse(post.html) # select votes and comments is_voted = False if request.me: comments = Comment.objects_for_user(request.me).filter(post=post).all() is_voted = PostVote.objects.filter(post=post, user=request.me).exists() else: comments = Comment.visible_objects().filter(post=post).all() context = { "post": post, "comments": comments, "comment_form": CommentForm(), "reply_form": ReplyForm(), "is_voted": is_voted, } # TODO: make pretty mapping here in future if post.type == Post.TYPE_BATTLE: context["comment_form"] = BattleCommentForm() try: return render(request, f"posts/show/{post.type}.html", context) except TemplateDoesNotExist: return render(request, "posts/show/post.html", context)
def create(self, validated_data): comment = validated_data['comment'] movie_id = validated_data['movie_id'] # print(validated_data) # # Get movie object try: movie = Movie.objects.get(id=movie_id) except Movie.DoesNotExist: raise serializers.ValidationError( 'Thread does not exist, please enter correct thread id') # # Get the requesting user user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user else: raise serializers.ValidationError( 'Must be authenticated to create post') # Create the post comment = Comment(comment=comment, movie=movie, user=user) # print(comment) # Update the thread last_activity to post creation time comment.save() return comment
def post_detail(request, postid): """ Returns a single Post object based on the post ID (pk) and render it to the 'postdetail.html' template. Return a 404 error if the post is not found. """ user = request.user if user.is_authenticated: if request.method == "POST": user = request.user comment = request.POST['comment'] post = get_object_or_404(Post, pk=postid) if comment.strip() == '': messages.error(request, 'Comment message is required.') return redirect('post_detail', postid=post.pk) comment = Comment(user=user, comment=comment, post=post) comment.save() messages.success(request, 'Thanks for your comment.') return redirect('post_detail', postid=post.pk) current_post = get_object_or_404(Post, pk=postid) current_post.views += 1 current_post.save() comments = Comment.objects.all().filter(post=postid) context = { 'post': current_post, 'comments': comments, } return render(request, 'postdetail.html', context)
def displayPost(request, username, post_number): post = Post.objects.get(user=User.objects.get(username=username), id=post_number) comments = Comment.objects.filter(post=post) # generate or handle comment form. if request.method == "POST": comment_text = request.POST.get('the_comment') comment = Comment(body=comment_text, post=post, user=request.user) comment.save() user = request.user.username num_comments = post.comment_set.count() response_data = { 'comment': str(comment), 'comment_id': comment.id, 'user': user, 'comment_count': num_comments } return JsonResponse(response_data) else: comment_form = CommentForm() reply_form = ReplyForm() num_comments = post.comment_set.count() context = { 'post': post, 'comments': comments, 'num_comments': num_comments, 'comment_form': comment_form, 'reply_form': reply_form # not initially in template. generated via ajax call if user clicks on reply link. } return render(request, 'posts/single_post.html', context)
def new(request): if not request.user.is_authenticated(): return HttpResponseForbidden user = request.user data = json.loads(request.body.decode('utf-8')) review = get_object_or_404(Review, id=data['reviewId']) comment = Comment(body=data['body'], user=user, review=review, user_name=("%s %s" % (user.first_name, user.last_name))) try: comment.save() except: return HttpResponseBadRequest() return JsonResponse( { 'userName': comment.user_name, 'userId': comment.user_id, 'reviewId': comment.review_id, 'body': comment.body }, safe=False)
def sync_comment(self): comments_map = {} root_header = None root_comment = None for comment in self.comments(): dot() if root_header is None or root_header.object_id != comment.nid: root_comment = Comment.objects.get_or_create_root_comment( self.node_ctype, comment.nid)[0] update_comments_header(Comment, instance=root_comment) filters = self.formats_filtering.get(comment.format, self.formats_filtering[1]) filtered_comment = self.call_filters(comment.comment, filters) time_created = timestamp_to_time(comment.timestamp) comment_instance = Comment( parent_id=comments_map[comment.pid] if comment.pid else root_comment.id, object_id=comment.nid, content_type=self.node_ctype, subject=comment.subject, created=time_created, updated=time_created, user_id=self.users_map.get(comment.uid), user_name=comment.name, is_public=True, is_locked=root_comment.is_locked, original_comment=TextVal( self.filter_formats.get(comment.format, 'raw') + ':' + comment.comment), ) comment_instance.save() Comment.objects.filter(pk=comment_instance.pk).update( filtered_comment=filtered_comment) comments_map[comment.cid] = comment_instance.pk
def bug(request, bugid): """ View for single bug, also handles adding comments to bug """ if request.method == "POST": userid = request.user comment = request.POST['comment'] ticket = get_object_or_404(Ticket, pk=bugid) if comment == '': messages.error(request, 'Comment message is required.') return redirect('/tickets/bug/' + bugid) comment = Comment(userid=userid, comment=comment, ticketid=ticket) comment.save() messages.success(request, 'Thanks for your comment.') return redirect('/tickets/bug/' + bugid) else: current_bug = get_object_or_404(Ticket, pk=bugid) comments = Comment.objects.all().filter(ticketid=bugid) votes = Vote.objects.all().filter(ticket=bugid).count() context = {'bug': current_bug, 'comments': comments, 'votes': votes} return render(request, 'tickets/bug.html', context)
def handle(self, *args, **kwargs): """ users = list(User.objects.all()) for i in range(100): q = Event() q.author = random.choice(users) q.title = u'title {}'.format(i) q.text = u'text {}'.format(i) q.is_published = True q.save() print "completed" """ users = list(User.objects.all()) b = [] p = [] c = [] for _ in range(10): b.append(Blog.objects.create()) for i in range(100): t = Event(author=random.choice(users), title = u'title {}'.format(i), text = u'text {}'.format(i), is_published = True, blog=random.choice(b)) p.append(t) t.save() Tag.objects.create(name='tag{}'.format(i)) # TODO tags.add(tag) for i in range(1000): com = Comment(author = random.choice(users), event = random.choice(p), text=u'text {}'.format(i)) c.append(com) com.save() print "completed"
def detail_view(request, slug): cart = Cart.objects.get_cart(request) query = get_object_or_404(Product, slug=slug) com = query.comments.all() if request.method == 'POST': if request.user.is_authenticated: comment = request.POST.get('comment', None) rating = request.POST.get('option', None) if comment is not None and rating is not None: new_comment = Comment(content=comment, author=request.user, rating=rating) new_comment.save() query.comments.add(new_comment) var = request.POST.get('foo') if var == 'remove': cart.product.remove(query) if var == 'add': cart.product.add(query) if query in cart.product.all(): change = 1 else: change = 2 print(request.POST) context = { 'qs': query, 'com': com, 'cart': cart, 'change': change, 'comm_access': comment_is_access(request, qery) } return render(request, 'shop/detail_view.html', context)
def test_blog_comments_view_comment(self, comment): blog_post = Post(title='Sample post', content='Sample content', author=self.user_with_blog, status='p', blog=self.user_with_blog.blog) blog_post.save() if comment: comment = Comment(author=self.user_with_blog, post=blog_post, comment='test comment') comment.save() comment_count = 1 else: comment_count = 0 self.assertTrue( self.client.login(username='******', password='******')) target = reverse('blog:blog_comments') response = self.client.get(target) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'blog/comments_list.html') self.assertEqual(response.context['comments'].count(), comment_count)
def migrate_comments(self): for legacy_comment in LegacyComment.objects.all(): assert isinstance(legacy_comment, LegacyComment) date_naive = datetime.utcfromtimestamp(legacy_comment.timestamp) date = timezone.make_aware(date_naive, timezone.utc) comment = Comment() comment.body = legacy_comment.comment comment.created = date comment.public = not legacy_comment.officer comment.user_id = legacy_comment.poster_id # this is erroring if legacy_comment.section == 0: continue if legacy_comment.section == 1: continue if legacy_comment.section == 2: continue if legacy_comment.section == 5: continue comment.content_type_id = { # i dont know what the keys are for the different content types 0: 1, # user manager 1: 2, # application 2: 3, # fodder vote 3: 4, # quote 4: 5, # screenshot 5: 6 # leadership application }.get(legacy_comment.section) comment.object_id = legacy_comment.reference comment.save()
def create_comment(request, id): product = Product.objects.get(id=id) c = Comment(comment_body=request.GET.get('body', 'No text'), comment_author=request.user, comment_product=product) c.save() return redirect('/product/%s/' % product.id)
def comment_post(request, boardno, userid, text): user = get_object_or_404(User, id=userid) board = get_object_or_404(Board, id=boardno) comment = Comment(text=text, writer=user, board=board) print(comment) comment.save() return Response({"message": "data input!", "data": request.data})
def random_comment(recipe): length = random.randint(50, 1000) text = "".join([random.choice(string.printable) for _ in range(length)]) user = random.choice( User.objects.filter(is_staff=False, profile__payment_status=3)) comment = Comment(recipe=recipe, user=user, text=text) comment.save()
def art_comment(request, art_pk): #art = models.Art.objects.filter(id=int(art_pk)) #方法1 art = get_object_or_404(models.Art, pk=art_pk) #方法2 if request.method == "POST": form = CommentForm(data=request.POST) if form.is_valid(): #评论表单合法 cmt = Comment(name=form.cleaned_data['name'], title=form.cleaned_data['title'], text=form.cleaned_data['text'], art=art) cmt.save() comment_list = art.comment_set.all() #通过外键反查所有评论 comment_count = comment_list.count(), context = dict( art=art, form=form, comment_list=comment_list, comment_count=comment_count, ) return render(request, "detail_handler.html", context=context) else: comment_list = art.comment_set.all() # 通过外键反查所有评论 comment_count = comment_list.count(), context = dict( art=art, form=form, comment_list=comment_list, comment_count=comment_count, ) flash(request, "error", "用户提交评论失败!") return render(request, "detail_handler.html", context=context) return redirect(art)
def sync_comment(self): comments_map = {} root_header = None root_comment = None for comment in self.comments(): dot() if root_header is None or root_header.object_id != comment.nid: root_comment = Comment.objects.get_or_create_root_comment(self.node_ctype, comment.nid)[0] update_comments_header(Comment, instance=root_comment) filters = self.formats_filtering.get(comment.format, self.formats_filtering[1]) filtered_comment = self.call_filters(comment.comment, filters) time_created = timestamp_to_time(comment.timestamp) comment_instance = Comment( parent_id=comments_map[comment.pid] if comment.pid else root_comment.id, object_id=comment.nid, content_type=self.node_ctype, subject=comment.subject, created=time_created, updated=time_created, user_id=self.users_map.get(comment.uid), user_name=comment.name, is_public=True, is_locked=root_comment.is_locked, original_comment=TextVal(self.filter_formats.get(comment.format, 'raw') + ':' + comment.comment), ) comment_instance.save() Comment.objects.filter(pk=comment_instance.pk).update(filtered_comment=filtered_comment) comments_map[comment.cid] = comment_instance.pk
def bug(request, bugid): """ View the details of a specific bug """ user = request.user if user.is_authenticated: if request.method == "POST": user = request.user comment = request.POST['comment'] ticket = get_object_or_404(Ticket, pk=bugid) if comment.strip() == '': messages.error(request, 'Comment message is required.') return redirect('bug', bugid=ticket.pk) comment = Comment(user=user, comment=comment, ticket=ticket) comment.save() messages.success(request, 'Thanks for your comment.') return redirect('bug', bugid=ticket.pk) current_bug = get_object_or_404(Ticket, pk=bugid) comments = Comment.objects.all().filter(ticket=bugid) votes = Vote.objects.all().filter(ticket=bugid).count() context = { 'bug': current_bug, 'comments': comments, 'votes': votes } return render(request, 'bug.html', context)
def add_comment(request): data = json.loads(request.body) user = User.objects.get(id=data["user"]) recipe = Recipe.objects.get(id=data["recipe"]) comment = Comment(user=user, recipe=recipe, text=data["text"]) comment.save() response_data = {"comment": comment.json()} return JsonResponse(data=response_data)
def render_post(request, post, context=None): # render "raw" newsletters if post.type == Post.TYPE_WEEKLY_DIGEST: return HttpResponse(post.html) # select votes and comments if request.me: comments = Comment.objects_for_user(request.me).filter(post=post).all() is_bookmark = PostBookmark.objects.filter(post=post, user=request.me).exists() is_voted = PostVote.objects.filter(post=post, user=request.me).exists() upvoted_at = int( PostVote.objects.filter( post=post, user=request.me).first().created_at.timestamp() * 1000) if is_voted else None subscription = PostSubscription.get(request.me, post) else: comments = Comment.visible_objects(show_deleted=True).filter( post=post).all() is_voted = False is_bookmark = False upvoted_at = None subscription = None # order comments comment_order = request.GET.get("comment_order") or "-upvotes" if comment_order in POSSIBLE_COMMENT_ORDERS: comments = comments.order_by( comment_order, "created_at") # additionally sort by time to preserve an order # hide deleted comments for battle (visual junk) if post.type == Post.TYPE_BATTLE: comments = comments.filter(is_deleted=False) comment_form = CommentForm(initial={'text': post.comment_template} ) if post.comment_template else CommentForm() context = { **(context or {}), "post": post, "comments": comments, "comment_form": comment_form, "comment_order": comment_order, "reply_form": ReplyForm(), "is_bookmark": is_bookmark, "is_voted": is_voted, "upvoted_at": upvoted_at, "subscription": subscription, } # TODO: make a proper mapping here in future if post.type == Post.TYPE_BATTLE: context["comment_form"] = BattleCommentForm() try: return render(request, f"posts/show/{post.type}.html", context) except TemplateDoesNotExist: return render(request, "posts/show/post.html", context)
def add_comment(request, npk): news = News.objects.get(pk=npk) ctxt = request.POST.get('msg') cname = request.POST.get('name') cmail = request.POST.get('email') new_comment = Comment(name=cname, email=cmail, txt=ctxt, news=news) new_comment.save() news.comment_set.add(new_comment) return redirect('news:news_detail', pk=npk)
def process_comment_reply(update: Update): if not update.message.reply_to_message: return user = get_bot_user(update) if not user: return comment_url_entity = [ entity["url"] for entity in update.message.reply_to_message.entities if entity["type"] == "text_link" and COMMENT_URL_RE.match(entity["url"]) ] if not comment_url_entity: log.info(f"Comment url not found in: {update.message.reply_to_message.entities}") return reply_to_id = COMMENT_URL_RE.match(comment_url_entity[0]).group(1) reply = Comment.objects.filter(id=reply_to_id).first() if not reply: log.info(f"Reply not found: {reply_to_id}") return is_ok = Comment.check_rate_limits(user) if not is_ok: send_telegram_message( chat=Chat(id=update.effective_chat.id), text=f"🙅♂️ Извините, вы комментировали слишком часто и достигли дневного лимита" ) return text = update.message.text or update.message.caption if not text: send_telegram_message( chat=Chat(id=update.effective_chat.id), text=f"😣 Сорян, я пока умею только в текстовые ответы" ) return comment = Comment.objects.create( author=user, post=reply.post, reply_to=Comment.find_top_comment(reply), text=text, useragent="TelegramBot (like TwitterBot)", metadata={ "telegram": update.to_dict() } ) new_comment_url = settings.APP_HOST + reverse("show_comment", kwargs={ "post_slug": comment.post.slug, "comment_id": comment.id }) send_telegram_message( chat=Chat(id=update.effective_chat.id), text=f"➜ [Отвечено]({new_comment_url}) 👍" )
def create_comment(request, post_slug): post = get_object_or_404(Post, slug=post_slug) if not post.is_commentable and not request.me.is_moderator: raise AccessDenied(title="Комментарии к этому посту закрыты") if request.POST.get("reply_to_id"): ProperCommentForm = ReplyForm elif post.type == Post.TYPE_BATTLE: ProperCommentForm = BattleCommentForm else: ProperCommentForm = CommentForm if request.method == "POST": form = ProperCommentForm(request.POST) if form.is_valid(): is_ok = Comment.check_rate_limits(request.me) if not is_ok: raise RateLimitException( title="🙅♂️ Вы комментируете слишком часто", message= "Подождите немного, вы достигли нашего лимита на комментарии в день. " "Можете написать нам в саппорт, пожаловаться об этом.") comment = form.save(commit=False) comment.post = post if not comment.author: comment.author = request.me comment.ipaddress = parse_ip_address(request) comment.useragent = parse_useragent(request) comment.save() # update the shitload of counters :) request.me.update_last_activity() Comment.update_post_counters(post) PostView.increment_unread_comments(comment) PostView.register_view( request=request, user=request.me, post=post, ) SearchIndex.update_comment_index(comment) LinkedPost.create_links_from_text(post, comment.text) return redirect("show_comment", post.slug, comment.id) else: log.error(f"Comment form error: {form.errors}") return render( request, "error.html", { "title": "Какая-то ошибка при публикации комментария 🤷♂️", "message": f"Мы уже получили оповещение и скоро пофиксим. " f"Ваш коммент мы сохранили чтобы вы могли скопировать его и запостить еще раз:", "data": form.cleaned_data.get("text") }) raise Http404()
def perform_destroy(self, instance): # delete all answers's comment when answer deleted. # TODO: delete all answer votes question = Question() comment = Comment() comments = instance.get("comments") for c in comments: comment.remove({"_id": ObjectId(c)}) self.answer.remove({"_id": instance.get("_id")}) question.collection.update({"_id": instance.get("question_id")}, {"$inc": {"answers_number": -1}})
def save(self, commit: bool = True) -> Comment: comment = Comment( message=self.instance.message, content=self.instance.content, parent=self.instance.parent, ) comment.save() return comment
def test_bulk_delete_successfully_deletes_comments(self): Comment.objects.bulk_create([ Comment(user=self.user, thread=self.thread), Comment(user=self.user, thread=self.thread), ]) comments = Comment.objects.all() Comment.objects.bulk_delete(comments) self.assertEqual(Comment.objects.count(), 0)
def add_comment(request): username = request.session["username"] content = request.POST["content"] article_id = request.POST["article_id"] user = User.objects.get(username=username) article = Article.objects.get(id=article_id) print article_id comment = Comment(content=content, article=article, user=user) comment.save() return HttpResponseRedirect("/articles/show_article/?id=%s" % article_id)
def migrate_comments(self): for legacy_comment in LegacyComment.objects.all(): assert isinstance(legacy_comment, LegacyComment) date_naive = datetime.utcfromtimestamp(legacy_comment.timestamp) date = timezone.make_aware(date_naive, timezone.utc) comment = Comment() comment.body = legacy_comment.comment comment.created = date comment.public = not legacy_comment.officer comment.user_id = legacy_comment.poster_id # this is erroring if legacy_comment.section == 0: continue if legacy_comment.section == 1: continue if legacy_comment.section == 2: continue if legacy_comment.section == 5: continue comment.content_type_id = { # i dont know what the keys are for the different content types 0: 1, # user manager 1: 2, # application 2: 3, # fodder vote 3: 4, # quote 4: 5, # screenshot 5: 6 # leadership application }.get(legacy_comment.section) comment.object_id = legacy_comment.reference comment.save()
def post_handler(request): # JSON post body of what you post to a posts' comemnts # POST to http://service/posts/{POST_ID}/comments output = { "query": "addComment", } # change body = request.POST to body = request.body.decode('utf-8'), # because request.POST only accepts form, but here is json format. # change new_comment.comment to new_comment.content, # because that's how it defined in comment model. try: body = request.body.decode('utf-8') comment_info = loads(body) comment_info = comment_info['comment'] new_comment = Comment() new_comment.contentType = comment_info['contentType'] new_comment.content = comment_info['comment'] new_comment.published = comment_info['published'] new_comment.author = Author.objects.filter(id=comment_info['author']['id']).first() new_comment.parentPost = Post.objects.filter(id=post_id).first() new_comment.save() output['type'] = True output['message'] = "Comment added" except Exception as e: output['type'] = False output['message'] = "Comment not allowed" output['error'] = str(e) finally: return JsonResponse(output)
def get_parent_object_kwargs(request): """ Format parameters for sql and choosing root by filters. """ parent = parse_int(request.query_params.get(PARENT_FILTER_KEY)) if parent: return dict(id=parent) content_type = parse_int(request.query_params.get(CONTENT_TYPE_FILTER_KEY)) object_id = parse_int(request.query_params.get(OBJECT_ID_FILTER_KEY)) if content_type and content_type == Comment.get_content_type().id and object_id: return dict(id=object_id) raise Comment.DoesNotExist()
def delete(cls, collection_id): collection = cls.objects.get_or_404(id=collection_id) if collection.owner != g.user: raise Forbidden('Only collection owner can delete collection') if collection.public else NotFound() Comment.delete_from_collection(collection) Item.delete_from_collection(collection) logger.info('Deleting {} ...'.format(collection)) super(cls, collection).delete() logger.info('Deleting {} done'.format(collection))
def tutorial_api(request): if request.method == "POST": print(request.body) _body = json.loads(request.body) try: new_comment = Comment(author=_body["author"], comment=_body["comment"]) new_comment.save() except Exception as e: print(e) rtn_list = json_encoder.serialize_to_json(Comment.objects.all().values()) return HttpResponse(rtn_list, content_type="application/json")
def create(self, validated_data): profile = validated_data['profile'] item_type = 'GRP' group = validated_data['group'] comment = validated_data['comment'] comment_obj = Comment(profile=profile, item_type=item_type, group=group, comment=comment) comment_obj.save() return comment_obj
def post(self, request: HttpRequest, board_id: int, article_id: int): data = JSONParser().parse(request) data[self.lookup_article_kwargs] = article_id serializer = CommentSerializer(data=data) if serializer.is_valid(): #serializer.save() comment = Comment() comment.add_root(contents=data['contents'], article_id=article_id) return Response({'mes': 'success'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, validated_data): profile = validated_data['profile'] item_type = 'IMG' image = validated_data['image'] comment = validated_data['comment'] comment_obj = Comment(profile=profile, item_type=item_type, image=image, comment=comment) comment_obj.save() return comment_obj
def test_delete_comment(self): sound = Sound.objects.get(id=19) user = User.objects.get(id=2) current_num_comments = sound.num_comments comment = Comment(content_object=sound, user=user, comment="Test comment") sound.add_comment(comment) comment.delete() sound = Sound.objects.get(id=19) self.assertEqual(current_num_comments, sound.num_comments) self.assertEqual(sound.is_index_dirty, True)
def new_comment(request): # saving the poted comment if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment() comment.book = form.cleaned_data.get("book") comment.chapter = form.cleaned_data.get("chapter") comment.example = form.cleaned_data.get("example") comment.page = form.cleaned_data.get("page") comment.title = form.cleaned_data.get("title") comment.body = form.cleaned_data.get("body") comment.email = form.cleaned_data.get("email", "Anonymous") comment.save() return HttpResponseRedirect( '/comments/get/?book={0}&chapter={1}&example={2}&page={3}'.format( comment.book, comment.chapter, comment.example, comment.page ) ) else: book = request.POST.get('book', '') chapter = request.POST.get('chapter', '') example = request.POST.get('example', '') page = request.POST.get('page', '') return HttpResponseRedirect( '/comments/new/?book={0}&chapter={1}&example={2}&page={3}'.format( book, chapter, example, page ) ) # retriving comment parameters book = request.GET.get('book', '') chapter = request.GET.get('chapter', '') example = request.GET.get('example', '') page = request.GET.get('page', '') initial_values = { 'book': book, 'chapter': chapter, 'example': example, 'page': page } form = CommentForm(initial = initial_values) context = { 'form': form, 'book': book, 'chapter': chapter, 'example': example, 'page': page } context.update(csrf(request)) return render(request, 'comments/new_comment.html', context)
def comment_app(request): if request.method == 'POST': c_author = request.POST['author'] c_email = request.POST['email'] c_url = request.POST['url'] c_content = request.POST['content'] c_obj_class = request.POST['obj_class'] try: c_obj_id = int(request.POST['obj_id']) except ValueError: raise Http404() p = Comment(author=c_author, email=c_email, url=c_url, content=c_content, objclass=c_obj_class, objid=c_obj_id) p.save() return HttpResponse("评论成功,请返回并刷新页面。")
def add(request): print "Hit add request for comment" r = '/' if request.method =='POST': form = CommentForm(request.POST) #print repr(form.cleaned_data) #print request.POST if form.is_valid(): d = form.cleaned_data #print d['suid'] if suid_store.check(d['suid']): suid_store.add(d['suid']) suid_store.trim() c = Comment() p = d['parent'].split(':') pt = Ticket r = '/tickets/' print p[0] if p[0] in ('ticket','Ticket'): pt = Ticket r = '/tickets/' elif p[0] in ('comment','com','Comment','comments','Comments'): pt = Comment r = '/comments/' #print r #Insert other comment parents here try: p = pt.objects.get(id=int(p[1])) #print "Got model of type " + str(type(pt)) r += str(p.id) + '/' except: #print 'Cannot get model of type ' + str(type(pt)) return HttpResponse('Invalid Parent') #c.content_type = ContentType.objects.get_for_model(pt) c.parent = p c.submittedby = request.user.member c.submittedtime = datetime.datetime.now() c.content = d['content'] c.save() #print d['files'] fs = getfilesfromfields(d['files'],d['autofiles']) if fs: print fs c.attachedfiles.add(*fs) c.save() #print "Id for new comment", c.id #print r else: print "Suid seen before" else: print "Form is invalid" #print r return HttpResponseRedirect(r)
def test_user_can_delete_comments(self): self.assertTrue(self.login) resource = self.create_resources() comment = Comment( id=200, author=self.user, resource=resource, content="Test comment" ) comment.save() response = self.client.delete( '/comment/200', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertContains(response, "success")
def get_all_tags(cls, assessment, json_encode=True): root = SummaryText.objects.get(title='assessment-{pk}'.format(pk=assessment.pk)) tags = SummaryText.dump_bulk(root) if root.assessment.comment_settings.public_comments: descendants=root.get_descendants() obj_type = Comment.get_content_object_type('summary_text') comments=Comment.objects.filter(content_type=obj_type, object_id__in=descendants) tags[0]['data']['comments'] = Comment.get_jsons(comments, json_encode=False) if json_encode: return json.dumps(tags, cls=HAWCDjangoJSONEncoder) else: return tags
def test_user_can_edit_comments(self): self.assertTrue(self.login) resource = self.create_resources() comment = Comment( id=200, author=self.user, resource=resource, content="Test comment" ) comment.save() json_data = json.dumps({'content': 'Another Content', }) response = self.client.put( '/comment/200', json_data, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertContains(response, "success")
def post(self, request, *args, **kwargs): if not request.user.is_authenticated(): return Response(status.HTTP_401_UNAUTHORIZED) ct = ContentType.objects.get_for_model(MODELS_MAPPINGS[kwargs['model']]) try: obj = ct.get_object_for_this_type(pk=kwargs['object_id']) except ObjectDoesNotExist: raise ErrorResponse(status.HTTP_404_NOT_FOUND) form = CommentForm(request.POST) if not form.is_valid(): raise ErrorResponse(status.HTTP_400_BAD_REQUEST) data = { 'content_type': ct, 'object_id': kwargs['object_id'], 'user': request.user, 'created': datetime.datetime.now(), 'content': form.cleaned_data['content'], } parent = form.cleaned_data['parent'] if parent: instance = parent.add_child(**data) else: instance = Comment.add_root(**data) if request.is_ajax(): return Response(status.HTTP_201_CREATED) return HttpResponseRedirect(obj.get_absolute_url())
def testReportComment(self): # Try to view form anonymously # (but get redirected because not authenticated) url = reverse('report_comment', args=[self.comment.id]) response = self.client.get(url) self.assertEqual(response.status_code, 302) # Log in self.client.login(username=self.eusa_staff.username, password="") # View form url = reverse('report_comment', args=[self.comment.id]) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertIn('form', response.context) self.assertIn('comment', response.context) self.assertEqual(self.comment, response.context['comment']) # Report post = {'reason': 'Unacceptable'} response = self.client.post(url, post) self.assertEqual(response.status_code, 302) self.assertTrue(Report.objects.filter( content_type=Comment.get_content_type(), object_id=self.comment.id))
def show(request, map_id, slug): """ Metoda zwraca stronę mapy o wskazanym :mod:`map_id`. :param map_id: identyfikator mapy w bazie danych :param slug: przyjazny adres mapy, ułatwia wyszukiwanie mapy w pasku przeglądarki :returns: obiekt mapy, formularz komentarza, komentarze """ map = Map.objects.get(pk=map_id) comments = map.comment_set.order_by('-created_at') times = map.time_set.order_by('-created_at')[:10] comment = Comment() comment.map = map form = CommentForm(instance=comment) return direct_to_template(request, 'maps/show.html', { 'map': map, 'form': form, 'times': times,\ 'comments': comments, 'center' : map.getcenter() })
def render_comment_list(context, obj): return { 'qs': Comment.get_for_object(obj), 'content_type': ContentType.objects.get_for_model(obj), 'obj': obj, 'perms': context['perms'], 'user': context['user'] }
def update_comment(self): """ Creates the shadow comment object to hold this document's place in a commment thread, if this document is a reply to comments. """ # Create comment objects only when the doc is public. That way, # subscription signals are fired at the right moment -- the comment is # public and viewable. parent = None if self.in_reply_to: try: parent = self.in_reply_to.document except Document.DoesNotExist: pass if parent and self.is_public(): # Only create a comment object if we are public. try: comment = self.comment except Comment.DoesNotExist: comment = Comment() comment.user = self.author comment.removed = False comment.document = parent comment.comment_doc = self comment.save() else: # If we've gone non-public, mark the comment removed rather # than deleting. That way, we don't re-fire subscriptions if # the doc is only temporarily un-published. try: self.comment.removed = True self.comment.save() except Comment.DoesNotExist: pass
def handle(self, *args, **options): users = list(User.objects.all()) for i in range(10): t = Topic() t.name = u'Topic Name {}'.format(i) t.description = u'Topic Description {}'.format(i) t.save() topics = list(Topic.objects.all()) for j in range(100): q = Question() q.author = random.choice(users) q.title = u'title {}'.format(j) q.text = u'text {}'.format(j) q.pub_date = datetime.datetime.now() q.is_published = True q.save() q.topics = random.sample(topics, random.randint(1, 6)) questions = list(Question.objects.all()) for k in range(100): c = Comment() c.author = random.choice(users) c.question = random.choice(questions) c.text = u'text {}'.format(k) c.pub_date = datetime.datetime.now() c.save()
def show(request, id, slug='a'): recipe = get_object_or_404(Recipe, id=id) categories = Category.objects.all() ingredients = recipe.ingredients.splitlines() comments = Comment.objects.filter(recipe=recipe).order_by('-date') if request.method == 'POST': form = AddCommentForm(request.POST) if form.is_valid(): comment = Comment() comment.text = form.cleaned_data['text'] comment.author = request.user comment.recipe = recipe comment.date = datetime.now() comment.save() else: form = AddCommentForm() return render(request, 'recipe/show.html', {'form': form, 'recipe': recipe, 'categories': categories, 'currentCat': recipe.category, 'ingredients': ingredients, 'comments': comments })
def add(request): comment = None func = lambda x: x if x is not None else '/static/user_account/pictures/unknown.png' try: if request.method == 'POST': pk = request.POST['pk'] text = request.POST['text'] task = Task.objects.get(pk=pk) comment = Comment(user=request.user, task=task, text=text) comment.save() set_achievements_at_commenting(request.user) comment = {"username": request.user.username, 'pk': request.user.pk, "url": func(UserProfile.objects.get_or_create_profile(request.user).pictureUrl), 'time': comment.creation_time} except Exception as e: print(e) return HttpResponse(status=500) return JsonResponse(comment, status=200)
def test_add_comment_to_post(self): post = Post( type='question', content='Ok', created_by=A2AUser.objects.get(pk=1) ) post.save() comment = Comment( parent=post, created_by=A2AUser.objects.get(pk=2) ) comment.save() self.check_num_comments() self.assertEqual( set(post.followed_by.all()), set([post.created_by, comment.created_by]) )
def render_comment_list(context, obj): return { 'next_page': context['request'].get_full_path(), 'qs': Comment.get_for_object(obj), 'content_type': ContentType.objects.get_for_model(obj), 'obj': obj, 'perms': context['perms'], 'user': context['user'] }
def prepare(self, obj): self.prepared_data = super(VideoIndex, self).prepare(obj) langs = obj.subtitlelanguage_set.exclude(language=u'') self.prepared_data['video_language'] = obj.language and '%s ++++++++++' % obj.language or '' self.prepared_data['languages'] = ['%s ++++++++++' % lang.language for lang in langs if lang.latest_subtitles()] self.prepared_data['comments_count'] = Comment.get_for_object(obj).count() self.prepared_data['languages_count'] = obj.subtitlelanguage_set.count() self.prepared_data['contributors_count'] = User.objects.filter(subtitleversion__language__video=obj).distinct().count() self.prepared_data['activity_count'] = obj.action_set.count() return self.prepared_data
def add_tag_comment(request): logger.debug('in add comment') if request.method == 'POST': # add a comment! form = request.POST #add a comment to a business' tag page if 'tid' in form: bid =form['bid'] b = Business.objects.get(id=bid) tid = form['tid'] t = Tag.objects.get(id=tid) if 'cid' not in form: #root reply nm = form['comment'] k = Comment(descr=nm,user=request.user,reply_to=None) k.save() tc = TagComment(business=b,tag=t,thread=k) tc.save() else: #reply to another comment submission nm = form['comment'] cid = form['cid'] parent = Comment.objects.get(id=cid) #parent comment k = Comment.objects.create(descr=nm,user=request.user,reply_to=parent) #new child k.save() comment_list = get_tag_comments(b,t) return render_to_response('ratings/discussion/thread.html', {'tag':t, 'business': b, 'comments': comment_list}) # add a comment to a business's page alone else: bid =form['bid'] b = Business.objects.get(id=bid) if 'cid' not in form: #root reply nm = form['comment'] k = Comment(descr=nm,user=request.user,reply_to=None) k.save() bc = BusinessComment(business=b,thread=k) bc.save() else: #reply to another comment submission nm = form['comment'] cid = form['cid'] parent = Comment.objects.get(id=cid) #parent comment k = Comment.objects.create(descr=nm,user=request.user,reply_to=parent) k.save() comment_list = get_business_comments(b) return render_to_response('ratings/discussion/thread.html', {'business':b, 'comments': comment_list})
def comment_service(request): user = None try: user = Account.objects.get(id=request.session['user_id']) except: user = None if not user: return HttpResponse('false') comment = request.POST.get('comment', '') pid = request.POST.get('pid', False) try: product = Product.objects.get(id=pid) comment_obj = Comment(comment_from=user, product=product, content=comment) comment_obj.save() except: return HttpResponse('false') return HttpResponse('true')
def get_assessment_descendants(cls, assessment_id, json_encode=True): """ Return all, excluding root """ root = cls.get_assessment_root_node(assessment_id) tags = SummaryText.dump_bulk(root) if root.assessment.comment_settings.public_comments: descendants = root.get_descendants() obj_type = Comment.get_content_object_type('summary_text') comments = Comment.objects.filter( content_type=obj_type, object_id__in=descendants ) tags[0]['data']['comments'] = Comment.get_jsons(comments, json_encode=False) if json_encode: return json.dumps(tags, cls=HAWCDjangoJSONEncoder) else: return tags
def add_comment(request): target_type = request.POST['type'] target_id = request.POST['tid'] content = request.POST['content'] reply_id = request.POST['reply_id'] reply_id = int(reply_id) target_id = int(target_id) from_user = request.user if from_user.is_anonymous(): return HttpResponse('403') if reply_id == -1: comment = Comment(target_id=target_id, target_type=target_type, content=content, from_user=from_user) else: reply = Comment.objects.get(id=reply_id) comment = Comment(target_id=target_id, target_type=target_type, content=content, from_user=from_user, reply=reply) comment.save() receiver = Articel.objects.get(id=target_id).author.email target_id = str(target_id) sem = mail_sender.SendMail() sem.comment_notify(receiver, from_user.username, content, target_id) return HttpResponse('304')
class CommentTests(_BaseIdeaTest): def setUp(self): super(CommentTests, self).setUp() self.comment = Comment(content="This is commenty comment", owner=self.user, idea=self.idea) self.comment.save() def tearDown(self): super(CommentTests, self).tearDown() self.comment.delete() def test_comment_view_contains_expected_information(self): url = reverse('comment-detail', kwargs={'pk':self.comment.pk}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, 'content') self.assertContains(response, 'owner') self.assertContains(response, 'idea')
def moderator_panel(request): if not request.user.is_authenticated(): return request_login(request) if not request.user.isModerator: messages.add_message(request, messages.ERROR, "Only moderators may access the moderator panel.") if request.is_ajax(): return HttpResponseForbidden("") else: return HttpResponseRedirect(reverse('frontpage')) if request.method == "POST": report_id = request.POST.get("report") report = Report.objects.get(id=report_id) action = request.POST.get("action") ajax_response_type = HttpResponse if action == "Hide": try: hide_action = HideAction() hide_action.moderator = request.user hide_action.reason = report.reason hide_action.content = report.content hide_action.save() report.delete() messages.add_message(request, messages.INFO, "Content hidden") except Report.DoesNotExist: messages.add_message(request, messages.ERROR, "Report not found") ajax_response_type = HttpResponseNotFound elif action == "Ignore": try: report.delete() messages.add_message(request, messages.INFO, "Report ignored") except Report.DoesNotExist: messages.add_message(request, messages.ERROR, "Report not found") ajax_response_type = HttpResponseNotFound else: messages.add_message(request, messages.ERROR, "Moderation action type not found") ajax_response_type = HttpResponseNotFound if request.is_ajax(): return ajax_response_type("") comment_reports = Report.objects.filter( content_type=Comment.get_content_type()) proposal_reports = Report.objects.filter( content_type=Proposal.get_content_type()) return render(request, "moderator_panel.html", {"comment_reports": comment_reports, "proposal_reports": proposal_reports})
def test_blog_comments_view_comment(self, comment): blog_post = Post(title='Sample post', content='Sample content', author=self.user_with_blog, status='p', blog=self.user_with_blog.blog) blog_post.save() if comment: comment = Comment(author=self.user_with_blog, post=blog_post, comment='test comment') comment.save() comment_count = 1 else: comment_count = 0 self.assertTrue( self.client.login(username='******', password='******')) target = reverse('blog:blog_comments') response = self.client.get(target) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'blog/comments_list.html') self.assertEqual(response.context['comments'].count(), comment_count)