Ejemplo n.º 1
0
def submit_reply(request, board_id, post_id):
    if not request.user.is_authenticated or request.user.username == "":
        return render(request, 'login.html', {})

    try:
        board = DefaultBoard.objects.get(pk=board_id)
        post = Post.objects.get(pk=post_id)

        if not board.access(request.user, access_type="post", default=False):
            context = {'board': board}
            return render(request, 'board_noperm.html', context)

        if request.method == "POST":
            form = ReplyForm(request.POST)
            if not form.is_valid():
                return Http404("Error submitting post.")

            text = form.cleaned_data['text']

            board.create_post(subject="Re: " + post.db_subject, text=text, author_name=request.user.username,
                              author_player=request.user, parent=post)
            return HttpResponseRedirect("/boards/" + str(board.id) + "/" + str(post.id) + "/")
        else:
            form = ReplyForm()
            context = {'board': board, 'board_id': board.id, 'post_id': post.id, 'form': form}
            return render(request, 'submit_reply.html', context)

    except (Board.DoesNotExist, Board.MultipleObjectsReturned, Post.DoesNotExist, Post.MultipleObjectsReturned):
        return Http404("Error accessing boards.")
Ejemplo n.º 2
0
    def post(self, request, id):
        form = ReplyForm(request.POST)
        response = Response.objects.get(pk=id)
        if not form.is_valid():
            print 'errors', form.errors
            context = {
                'form': form,
                'response': response,
            }
            return render(request, 'claims/responses/detail.html', context)

        parent = None
        if form.cleaned_data['comment_id']:
            parent = Comment.objects.get(pk=form.cleaned_data['comment_id'])

        print 'trying to make...'

        Comment.objects.create(user=request.user,
                               response=response,
                               parent=parent,
                               body=form.cleaned_data['body'])

        print 'made comment, redirecting'

        return redirect('response-detail', id=response.id)
Ejemplo n.º 3
0
def reply_to_question(request, question_id):
    question = Question.objects.get(id=int(question_id))
    form = ReplyForm(request.POST)
    if form.is_valid():
        question.reply = form.cleaned_data["text"]
        question.save()
    return redirect_user_to_homepage(request.user.profile.user_type)
Ejemplo n.º 4
0
def view(request, pk):

    if pk > 0:

	#database queries for bulletin info
	bulletin = Bulletin.objects.get(pk=pk)
	allreplies = Reply.objects.filter(thread__bulletin=bulletin)
	replies= allreplies.filter(public=True).order_by("-timestamp")
	privatecount = allreplies.filter(public=False).exclude(sender=bulletin.creator).count()
    else: return render(request, '404.html', {})

    if request.method == 'POST':
	form = ReplyForm(request.POST)
	if form.is_valid():
	    cleaned_data = form.clean()
	    if request.POST['visibility'] == 'Public':
		public = True
	    else: public = False
	    if request.user.userdata != bulletin.creator or public:
                message = cleaned_data['message']
                outmail.replyToBulletin(bulletin, message, request.user.userdata, public)

    #update page
    form = ReplyForm()
    resolveform = ResolverCreditForm()
    if request.user.is_authenticated and request.user.userdata == bulletin.creator:
	bulletinform = UpdateBulletinForm()
    else: bulletinform = {}
    return render(request, 'bulletin.html', {'bulletin':bulletin, 'replies':replies, 'privatecount':privatecount, 'form':form, 'bulletinform':bulletinform, 'resolveform':resolveform})
Ejemplo n.º 5
0
def reply_to_question(request, question_id):
    question = Question.objects.get(id=int(question_id))
    form = ReplyForm(request.POST)
    if form.is_valid():
        question.reply = form.cleaned_data["text"]
        question.save()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Ejemplo n.º 6
0
def reply(request, mlist_fqdn, message_id_hash):
    """ Sends a reply to the list.
    TODO: unit tests
    """
    if request.method != 'POST':
        raise SuspiciousOperation
    form = ReplyForm(request.POST)
    if not form.is_valid():
        return HttpResponse(form.errors.as_text(),
                            content_type="text/plain", status=400)
    store = get_store(request)
    mlist = store.get_list(mlist_fqdn)
    if form.cleaned_data["newthread"]:
        subject = form.cleaned_data["subject"]
        headers = {}
    else:
        message = store.get_message_by_hash_from_list(mlist.name, message_id_hash)
        subject = message.subject
        if not message.subject.lower().startswith("re:"):
            subject = "Re: %s" % subject
        headers = {"In-Reply-To": "<%s>" % message.message_id,
                   "References": "<%s>" % message.message_id, }
    try:
        post_to_list(request, mlist, subject, form.cleaned_data["message"], headers)
    except PostingFailed, e:
        return HttpResponse(str(e), content_type="text/plain", status=500)
Ejemplo n.º 7
0
def comment(id):

    comment = Comment.query.get_or_404(id)
    authorid = comment.author_id
    postid = comment.post_id

    post = Post.query.get_or_404(postid)
    user = User.query.get_or_404(authorid)
    page = request.args.get('page', 1, type=int)

    form = ReplyForm()

    if form.validate_on_submit():
        user_url = url_for('user', username=user.username, _external=True)
        reply = Comment(body_html= '<a href="' + user_url + '">@' + user.username + '</a> ' + form.body.data,
                          timestamp=datetime.utcnow(),
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(reply)
        db.session.flush()
        r = comment.reply(reply)
        db.session.add(r)
        db.session.commit()

        flash('Your comment has been published.')
    commenturl = url_for('post', id=post.id, page=page, _external=True)
    if user.email:
        reply_notification(user, g.user, commenturl)
    return redirect(url_for('post', id=post.id, page=page))
Ejemplo n.º 8
0
def thread(request, pk):
    """Render a single thread's info, usually for the mailbox"""

    print 'made it!'
    thread = Reply_Thread.objects.get(id=pk)
    info={}

    #You have to belong to the thread to access it!
    if request.session['pk'] in [thread.bulletin.creator.pk, thread.replier.pk]:
	info.update({'thread':thread})
	new=[]
	for reply in thread.reply_set.exclude(sender__id=request.session['pk']).filter(read=False):
	    new.append(reply.id)
	    reply.read=True
	    reply.save()
	#Handle request to add replies to the thread
	if request.method == 'POST':
	    form = ReplyForm(request.POST)
	    if form.is_valid():
		cleaned_data = form.clean()
		if request.POST['visibility'] == 'Public':
		    public = True
		else: public = False
        #Maybe works?
		user = UserData.objects.get(pk==request.session['pk'])
		message = cleaned_data['message']
                outmail.replyWithThread(thread, message, user, public)
    #Filling out the necessary context
    form = ReplyForm()
    info.update({'form':form, 'new':new});
    return render(request, 'elements/replythread.html', info)
Ejemplo n.º 9
0
def reply(request, mlist_fqdn, message_id_hash):
    """ Sends a reply to the list.
    TODO: unit tests
    """
    if request.method != 'POST':
        raise SuspiciousOperation
    form = ReplyForm(request.POST)
    if not form.is_valid():
        return HttpResponse(form.errors.as_text(),
                            content_type="text/plain",
                            status=400)
    store = get_store(request)
    mlist = store.get_list(mlist_fqdn)
    if form.cleaned_data["newthread"]:
        subject = form.cleaned_data["subject"]
        headers = {}
    else:
        message = store.get_message_by_hash_from_list(mlist.name,
                                                      message_id_hash)
        subject = message.subject
        if not message.subject.lower().startswith("re:"):
            subject = "Re: %s" % subject
        headers = {
            "In-Reply-To": "<%s>" % message.message_id,
            "References": "<%s>" % message.message_id,
        }
    try:
        post_to_list(request,
                     mlist,
                     subject,
                     form.cleaned_data["message"],
                     headers,
                     attachments=request.FILES.getlist('attachment'))
    except PostingFailed, e:
        return HttpResponse(str(e), content_type="text/plain", status=500)
Ejemplo n.º 10
0
def bbs_topic(id):
    options = {"id": id}
    page = request.args.get('page', 0, type=int)
    topic = Topic.query.get(id)
    if not topic:
        return render_template("topic_not_found.html")

    count, num_pages, replies = get_page_query(Reply.query.replies_at_topic(topic.id), page, page_size=DEFAULT_PAGE_REPLIES)
    def pager_url(p, options):
        return generate_url(".bbs_topic", page=p, **options)

    if current_user.is_anonymous():
        form = None
    else:
        form = ReplyForm(request.form)

    if request.method == "POST":
        if current_user.is_anonymous():
            return redirect(url_for("auth.login", next=request.path) or "/")
        if form.validate():
            reply = Reply(section=topic.section, node=topic.node, user=current_user, topic=topic,
                content=form.data["content"], created=datetime.now(), floor=topic.reply_count+1)
            topic.last_reply_by = current_user.username
            topic.last_reply_at = datetime.now()
            topic.reply_count += 1
            current_user.profile.replies += 1
            node = topic.node
            node.reply_count += 1
            section = topic.section
            section.reply_count += 1
            db.session.add_all([reply, topic, current_user.profile, node, section])
            db.session.commit()

            return redirect(pager_url((reply.floor-1)/DEFAULT_PAGE_REPLIES, options))

        return render_template("topic.html", topic=topic, options=options, count=count, pager_url=pager_url,
                                num_pages=num_pages, page=page, replies=replies, form=form)

    topic.hits += 1
    db.session.commit()

    markdowner = Markdown()
    topic.content = markdowner.convert(topic.content)
    for r in replies:
        r.content = markdowner.convert(r.content)

    return render_template("topic.html", topic=topic,
                                            options=options,
                                            count=count,
                                            pager_url=pager_url,
                                            num_pages=num_pages,
                                            page=page,
                                            replies=replies,
                                            form=form
                            )
Ejemplo n.º 11
0
def reply(request,target_mail_id):
	"""docstring for send_mail"""
	tmail=get_object_or_404(Mail,id=target_mail_id)
	if request.POST:
		form=ReplyForm(request.POST)
		if form.is_valid():
			send_mail(tmail,form)
			return HttpResponseRedirect('/')
	else:
		form=ReplyForm()
	return render_to_response('reply.html',locals())
Ejemplo n.º 12
0
Archivo: views.py Proyecto: nonni/fruss
def get_thread_posts(request, thread_id):
    """
    Returns all posts in a thread, including the 'thread' post itself.
    """
    thread = get_object_or_404(Thread, pk=thread_id)
    if thread.hidden:
        raise Http404

    # Mark thread a read for user.
    read = UserRead.objects.get_or_create(user=request.user, thread=thread_id)[0]
    read.read = True
    read.save()

    if request.method == "POST":
        form = ReplyForm(request.POST)
        if form.is_valid():
            reply = form.save(commit=False)

            # TODO: Check if user is logged in
            reply.author = request.user
            reply.thread_id = thread_id
            reply.pub_date = datetime.now()
            reply.update = datetime.now()
            reply.save()
            thread.latest_post = reply
            thread.save()
            form = ReplyForm()  # Clear the form
            # Mark thread as unread for other users
            ur = UserRead.objects.all().filter(thread__exact=thread_id).exclude(user=request.user)
            for u in ur:
                u.read = False
                u.save()
            # Focus on new post after reply.
            return HttpResponseRedirect("%s?page=last#post_%s" % (reverse("thread", args=[thread.id]), reply.id))
    else:
        form = ReplyForm()

    post_list = Post.objects.all().filter(thread=thread_id, hidden=False)
    p = Paginator(post_list, 5)
    try:
        page = int(request.GET.get("page", "1"))
    except:
        page = p.num_pages
    try:
        posts = p.page(page)
    except (EmptyPage, InvalidPage):
        raise Http404

    return render_to_response(
        "dsf/thread_detail.html",
        {"thread": thread, "posts": posts, "form": form},
        context_instance=RequestContext(request),
    )
Ejemplo n.º 13
0
 def post(self, reply_id):
     reply = Reply.get(id=reply_id)
     if not reply or (reply.author != self.current_user and not self.current_user.is_admin):
         return self.redirect_next_url()
     user = self.current_user
     form = ReplyForm(self.request.arguments)
     if form.validate():
         reply = form.save(user=user, topic=reply.topic, reply=reply)
         reply.put_notifier()
         result = {'status': 'success', 'message': '评论修改成功',
                   'reply_url': reply.url}
         return self.send_result(result, reply.url)
     data = dict(form=form, reply=reply)
     return self.send_result_and_render(form.result, "reply/edit.html", data)
Ejemplo n.º 14
0
def reply():
    form = ReplyForm()
    if form.validate_on_submit():
        u = User.query.filter_by(id = g.user.id).first()
        t = Topic.query.filter_by(id = form.topic_id.data).first()
        reply = Reply(thread=t, author=u, content=form.content.data)
        db.session.add(reply)
        db.session.commit()
        flash("回复成功")
        return redirect(request.args.get("next") or url_for("index"))
    form.topic_id.data = request.args.get('topic_id', '')
    return render_template('reply.html',
        form = form,
        title = '新建')
Ejemplo n.º 15
0
def replies(request, mlist_fqdn, threadid):
    """Get JSON encoded lists with the replies and the participants"""
    chunk_size = 5
    offset = int(request.GET.get("offset", "1"))
    store = get_store(request)
    thread = store.get_thread(mlist_fqdn, threadid)
    mlist = store.get_list(mlist_fqdn)
    context = {
        'mlist': mlist,
        'threadid': threadid,
        'reply_form': ReplyForm(),
    }
    context["replies"] = _get_thread_replies(request,
                                             thread,
                                             offset=offset,
                                             limit=chunk_size)

    replies_tpl = loader.get_template('threads/replies.html')
    replies_html = replies_tpl.render(RequestContext(request, context))
    response = {
        "replies_html": replies_html,
        "more_pending": False,
        "next_offset": None,
    }
    if len(context["replies"]) == chunk_size:
        response["more_pending"] = True
        response["next_offset"] = offset + chunk_size
    return HttpResponse(json.dumps(response),
                        mimetype='application/javascript')
Ejemplo n.º 16
0
def client(request):
    """
    Render the client homepage.
    Grabs what is needed for the client: their projects / bids, notifications, and any questions
    on their projects
    """
    reply_form = ReplyForm()
    bids = Bid.objects.filter(
        project__client__id=request.user.id).order_by('-id')
    projects = Project.objects.filter(
        client_id=request.user.id).order_by('-id')
    questions = Question.objects.filter(
        project__client__id=request.user.id).order_by('-id')
    notifications = Notification.objects.filter(
        recipient__id=request.user.id).order_by('-id')
    context = {
        "bids": bids.order_by('-id')[:4],
        "bids_count": bids.count,
        "projects": projects.order_by('-id')[:],
        "projects_count": projects.count,
        "questions": questions.order_by('-id')[:],
        "questions_count": questions.count,
        "notifications": notifications.order_by('-id')[:1],
        "notifications_count": notifications.count,
        "reply_form": reply_form
    }
    return render(request, "client.html", context)
Ejemplo n.º 17
0
 def get(self, topic_id):
     topic_id = int(topic_id)
     page = force_int(self.get_argument('page', 0), 0)
     topic = Topic.get(id=topic_id)
     if not topic:
         raise tornado.web.HTTPError(404)
     category = self.get_argument('category', None)
     if not category:
         category = 'all'
     if category == 'all':
         reply_count = topic.reply_count
         url = topic.url
     elif category == 'hot':
         reply_count = orm.count(
             topic.get_replies(page=None, category=category))
         url = topic.url + '?category=hot'
     page_count = (reply_count + config.reply_paged -
                   1) // config.reply_paged
     if page == 0:
         page = page_count
     replies = topic.get_replies(page=page, category=category)
     form = ReplyForm()
     return self.render("topic/index.html",
                        topic=topic,
                        replies=replies,
                        form=form,
                        category=category,
                        page=page,
                        page_count=page_count,
                        url=url)
Ejemplo n.º 18
0
def comment():
    tid = request.args.get('tid')
    form = ReplyForm()
    if request.method == 'GET':
        pid = request.args.get('pid')
        pn = request.args.get('pn')
        if not pn:
            pn = 1
        else:
            pn = int(pn)
        if pn == 1:
            comment = Comment.query.filter_by(tid=tid).first()
        else:
            comment = None

        title = Comment.query.filter_by(tid=tid).first().title
        reply_list = Reply.query.filter_by(
            tid=tid).order_by('reply.rid').paginate(pn, MAX_REPLY_NUM_ONE_PAGE)
        return render_template('comment.html', pid = pid, tid = tid, title = title, comment = comment, pn = pn, \
                                                reply_list = reply_list, form = form)
    else:
        reply = Reply(tid = tid, userid = current_user.userid, nickname = current_user.nickname, \
                        content = form.content.data, post_time = get_now_time())

        comment = Comment.query.filter_by(tid=tid).first()
        comment.re += 1
        db.session.add(reply)
        db.session.commit()
        return redirect(request.referrer)
Ejemplo n.º 19
0
def show_thread(request, board_id, post_id):
    if not request.user.is_authenticated or request.user.username == "":
        return render(request, 'login.html', {})

    try:
        post = Post.objects.get(pk=post_id)
        board = post.db_board

        if not board.access(request.user, access_type="read", default=False):
            context = {'board': board}
            return render(request, 'board_noperm.html', context)

        can_post = board.access(request.user, access_type="post", default=False)

        plaintext = ansi.strip_ansi(post.db_text)
        setattr(post, 'plaintext', plaintext)
        post.mark_read(request.user, True)

        replies = Post.objects.filter(db_parent=post).order_by('db_date_created')
        for r in replies:
            plaintext = ansi.strip_ansi(r.db_text)
            setattr(r, 'plaintext', plaintext)
            r.mark_read(request.user, True)

        form = ReplyForm()
        context = {'board': board, 'post': post, 'replies': replies, 'can_post': can_post,
                   'board_id': board, 'post_id': post, 'form': form}

        return render(request, 'thread.html', context)

    except (Post.DoesNotExist, Post.MultipleObjectsReturned):
        return Http404("Error accessing boards.")
Ejemplo n.º 20
0
def show_comment(tid):
    form = ReplyForm()
    if request.method == 'GET':
        page = request.args.get('page')
        if not page:
            page = 1
        else:
            page = int(page)
        if page == 1:
            comment = Comment.query.get(tid)
        else:
            comment = None

        title = Comment.query.get(tid).title
        reply_list = Reply.query.filter_by(tid=tid).order_by(
            Reply.tid).paginate(page, MAX_REPLY_NUM_ONE_PAGE, False)
        return render_template('showcomment.html',
                               tid=tid,
                               title=title,
                               comment=comment,
                               page=page,
                               reply_list=reply_list,
                               form=form)
    else:
        reply = Reply(tid = tid, userid = current_user.userid, nickname = current_user.nickname, \
                        content = form.content.data, post_time = get_now_time())

        comment = Comment.query.get(tid)
        comment.re += 1
        reply.save()
        db.session.commit()
        return redirect(request.referrer)
Ejemplo n.º 21
0
def window_comment_reply(request):
    reply_form = ReplyForm(request.POST)
    if reply_form.is_valid():
        reply_dict = reply_form.cleaned_data
        window_id = request.user_meta['window_model'].id
        order_model = order.get_order_byid_bywin(window_id, reply_dict)
        order_dish_model = orderdish.get_order_dish_byid(order_model, reply_dict)
        if order_dish_model.comment_time:  # user can only make reply on comments
            if order_dish_model.reply_time is None:
                orderdish.update_reply(order_dish_model, reply_dict)
                return json_response(OK, CODE_MESSAGE.get(OK))
            else:
                return json_response(ORDER_DISH_REPLIED, CODE_MESSAGE.get(ORDER_DISH_REPLIED))
        else:
            return json_response(ORDER_STATUS_ERROR, CODE_MESSAGE.get(ORDER_STATUS_ERROR))
    else:
        return json_response(PARAM_REQUIRED, CODE_MESSAGE.get(PARAM_REQUIRED))
Ejemplo n.º 22
0
 def get(self, reply_id):
     if not self.has_permission:
         return
     reply = Reply.get(id=reply_id)
     if not reply:
         return self.redirect_next_url()
     form = ReplyForm(content=reply.content)
     return self.render("reply/edit.html", form=form, reply=reply)
Ejemplo n.º 23
0
 def post(self):
     if not self.has_permission:
         return
     page = int(self.get_argument('page', 1))
     topic_id = int(self.get_argument('topic_id', 0))
     topic = Topic.get(id=topic_id)
     if not topic_id:
         result = {'status': 'error', 'message': '无此主题,不能创建评论'}
         if self.is_ajax:
             return self.write(result)
         else:
             self.flash_message(result)
             return self.redirect_next_url()
     user = self.current_user
     form = ReplyForm(self.request.arguments)
     if form.validate():
         reply = form.save(user=user, topic=topic)
         if 'class="mention"' in reply.content:
             put_notifier(reply)
         result = {
             'status': 'success',
             'message': '评论创建成功',
             'content': reply.content,
             'name': reply.author.name,
             'nickname': reply.author.nickname,
             'author_avatar': reply.author.get_avatar(size=48),
             'author_url': reply.author.url,
             'author_name': reply.author.name,
             'author_nickname': reply.author.nickname,
             'reply_url': reply.url,
             'created': reply.created,
             'id': reply.id,
             'floor': reply.floor
         }
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(topic.url)
     if self.is_ajax:
         return self.write(form.result)
     self.flash_message(form.result)
     return self.render("topic/index.html",
                        form=form,
                        topic=topic,
                        category='index',
                        page=page)
Ejemplo n.º 24
0
 def get(self, request, id):
     form = ReplyForm()
     response = Response.objects.get(pk=id)
     context = {
         'form': form,
         'response': response,
     }
     return render(request, 'claims/responses/detail.html', context)
Ejemplo n.º 25
0
 def post(self, reply_id):
     if not self.has_permission:
         return
     reply = Reply.get(id=reply_id)
     if not reply or (reply.author != self.current_user and not self.current_user.is_admin):
         return self.redirect_next_url()
     user = self.current_user
     form = ReplyForm(self.request.arguments)
     if form.validate():
         reply = form.save(user=user, topic=reply.topic, reply=reply)
         result = {"status": "success", "message": "评论修改成功", "reply_url": reply.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(reply.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("reply/edit.html", form=form, reply=reply)
Ejemplo n.º 26
0
 def get(self, reply_id):
     if not self.has_permission:
         return
     reply = Reply.get(id=reply_id)
     if not reply or (reply.author != self.current_user
                      and not self.current_user.is_admin):
         return self.redirect_next_url()
     form = ReplyForm(content=reply.content)
     return self.render("reply/edit.html", form=form, reply=reply)
Ejemplo n.º 27
0
def reply(comment_id):
    comment = Comment.query.get_or_404(comment_id)
    form = ReplyForm()
    reply_id = request.args.get('reply_id')
    is_reply = bool(request.args.get('is_reply'))
    if form.validate_on_submit():
        if not is_reply:
            pids = ""
        else:
            result = Reply.query.with_entities(
                Reply.pids).filter_by(id=reply_id).first()
            pids = str(result[0]) + ':' + str(reply_id)
        reply = Reply(body=form.body.data,
                      author=current_user._get_current_object(),
                      comment=comment,
                      pids=pids)
        db.session.add(reply)
        return redirect(url_for('.post', id=comment.post_id))
    return render_template('post.html', form=form)
Ejemplo n.º 28
0
 def post(self, reply_id):
     if not self.has_permission:
         return
     reply = Reply.get(id=reply_id)
     if not reply:
         return self.redirect_next_url()
     user = self.current_user
     form = ReplyForm(self.request.arguments)
     if form.validate():
         reply = form.save(user=user, topic=reply.topic, reply=reply)
         result = {'status': 'success', 'message': '评论修改成功',
                 'reply_url': reply.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(reply.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("reply/edit.html", form=form, reply=reply)
Ejemplo n.º 29
0
 def post(self, reply_id):
     if not self.has_permission:
         return
     reply = Reply.get(id=reply_id)
     if not reply:
         return self.redirect_next_url()
     user = self.current_user
     form = ReplyForm(self.request.arguments)
     if form.validate():
         reply = form.save(user=user, topic=reply.topic, reply=reply)
         result = {'status': 'success', 'message': '评论修改成功',
                 'reply_url': reply.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(reply.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("reply/edit.html", form=form, reply=reply)
Ejemplo n.º 30
0
 def post(self):
     if not self.has_permission:
         return
     page = int(self.get_argument("page", 1))
     topic_id = int(self.get_argument("topic_id", 0))
     topic = Topic.get(id=topic_id)
     if not topic_id:
         result = {"status": "error", "message": "无此主题,不能创建评论"}
         if self.is_ajax:
             return self.write(result)
         else:
             self.flash_message(result)
             return self.redirect_next_url()
     user = self.current_user
     form = ReplyForm(self.request.arguments)
     if form.validate():
         reply = form.save(user=user, topic=topic)
         if 'class="mention"' in reply.content:
             put_notifier(reply)
         result = {
             "status": "success",
             "message": "评论创建成功",
             "content": reply.content,
             "name": reply.author.name,
             "nickname": reply.author.nickname,
             "author_avatar": reply.author.get_avatar(size=48),
             "author_url": reply.author.url,
             "author_name": reply.author.name,
             "author_nickname": reply.author.nickname,
             "reply_url": reply.url,
             "created": reply.created,
             "id": reply.id,
             "floor": reply.floor,
         }
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(topic.url)
     if self.is_ajax:
         return self.write(form.result)
     self.flash_message(form.result)
     return self.render("topic/index.html", form=form, topic=topic, category="index", page=page)
Ejemplo n.º 31
0
 def get(self, request, id):
     form = ResponseForm()
     reply_form = ReplyForm()
     claim = Claim.objects.get(pk=id)
     context = {
         'claim': claim,
         'form': form,
         'reply_form': reply_form,
         'responses': claim.response_set.all(),
     }
     return render(request, 'claims/detail.html', context)
Ejemplo n.º 32
0
 def get(self, topic_id):
     topic_id = int(topic_id)
     page = force_int(self.get_argument('page', 0), 0)
     topic = Topic.get(id=topic_id)
     if not topic:
         raise tornado.web.HTTPError(404)
     action = self.get_argument('action', None)
     category = self.get_argument('category', None)
     user = self.current_user
     if action and user:
         if action == 'up':
             if topic.user_id != user.id:
                 result = user.up(topic_id=topic_id)
             else:
                 result = {'status': 'info', 'message': '不能为自己的主题投票'}
         if action == 'down':
             if topic.user_id != user.id:
                 result = user.down(topic_id=topic_id)
             else:
                 result = {'status': 'info', 'message': '不能为自己的主题投票'}
         if action == 'collect':
             result = user.collect(topic_id=topic_id)
         if action == 'thank':
             result = user.thank(topic_id=topic_id)
         if action == 'report':
             result = user.report(topic_id=topic_id)
         if self.is_ajax:
             return self.write(result)
         else:
             self.flash_message(result)
             return self.redirect_next_url()
     if not category:
         category = 'all'
     if category == 'all':
         reply_count = topic.reply_count
         url = topic.url
     elif category == 'hot':
         reply_count = count(topic.get_replies(page=None,
                                               category=category))
         url = topic.url + '?category=hot'
     page_count = (reply_count + config.reply_paged -
                   1) // config.reply_paged
     if page == 0:
         page = page_count
     replies = topic.get_replies(page=page, category=category)
     form = ReplyForm()
     return self.render("topic/index.html",
                        topic=topic,
                        replies=replies,
                        form=form,
                        category=category,
                        page=page,
                        page_count=page_count,
                        url=url)
Ejemplo n.º 33
0
def show_review(request,
                review_slug,
                template_name="pdcts/review_details.html"):
    r = get_object_or_404(ProductReview, slug=review_slug)
    page_title = r.title

    reply_reviews = Review_Reply.approved.filter(review=r).order_by('-date')
    reply_form = ReplyForm()
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
Ejemplo n.º 34
0
Archivo: views.py Proyecto: nonni/fruss
def edit_post(request, post_id):
    post = get_object_or_404(Post, pk=post_id)
    if not request.user is post.author and not request.user.is_superuser:
        return HttpResponse("Access denied!")
    if request.method == "POST":
        form = ReplyForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            body = data["body"]
            post = get_object_or_404(Post, pk=post_id)
            post.body = body
            post.markdown = data["markdown"]
            post.update = datetime.now()
            post.save()
            return HttpResponse(markdown.markdown(post.body))
    if request.user.is_superuser or post.author is request.user:
        form = ReplyForm(post.__dict__)
        return render_to_response("dsf/post_edit.html", {"form": form, "post_id": post_id})
    else:
        return HttpResponse(_("Access denied!"))
Ejemplo n.º 35
0
def view_question(request,classes,lecture_number,noteslug,qpk):
    lectures = Lecture.objects.filter(slug=classes,
        lecture_number=lecture_number)
    note = Note.objects.filter(slug=noteslug)
    question = NoteQuestion.objects.filter(pk=qpk)
    replies = NoteReply.objects.filter(question=question)
    if request.POST:
        replyform = ReplyForm(request.POST)
        if replyform.is_valid():
            newreply = replyform.save(commit=False)
            newreply.author = User.objects.get(username=request.user)
            newreply.question = question[0]
            newreply.save()

            return HttpResponseRedirect('.')
    else:
        replyform = ReplyForm(request.POST)
    args = {}
    args.update(csrf(request))
    isauthor = (question[0].author == request.user.username) or request.user.is_superuser
    isnoteauthor = (note[0].author == request.user.username) or request.user.is_superuser
    args['form'] = replyform
    args['classes'] = lectures[0].course.classes
    args['lectureslug'] = classes
    args['lecture_number'] = lecture_number
    args['note'] = note[0]
    args['question'] = question[0]
    args['replies'] = replies
    args['isauthor'] = isauthor
    args['isnoteauthor'] = isnoteauthor
    return render_to_response('view_question.html', args)
Ejemplo n.º 36
0
def show_comment(comment_id):
    form = ReplyForm()
    reply_page = request.args.get('c_page', 1)
    deleted = request.args.get('deleted')
    post_id = request.args.get('post_id')
    requested_comment, replies, parent_post = get_comment_elements(
        comment_id, deleted, post_id)
    if form.validate_on_submit():
        return add_reply(requested_comment, form.reply.data, reply_page)
    return handle_page(endpoint='post.html',
                       count_arg='c_count',
                       page_id=reply_page,
                       page_arg='current_c',
                       items_lst=replies,
                       items_arg='replies',
                       original_comment=requested_comment,
                       post=parent_post,
                       comments=[requested_comment],
                       form=form,
                       deleted=str(deleted),
                       post_id=post_id,
                       comment=True)
Ejemplo n.º 37
0
def reply(request, mlist_fqdn, message_id_hash):
    """ Sends a reply to the list.
    TODO: unit tests
    """
    if request.method != 'POST':
        raise SuspiciousOperation
    form = ReplyForm(request.POST)
    if not form.is_valid():
        return HttpResponse(form.errors.as_text(),
                            content_type="text/plain", status=400)
    store = get_store(request)
    mlist = store.get_list(mlist_fqdn)
    message = store.get_message_by_hash_from_list(mlist.name, message_id_hash)
    subject = message.subject
    if not message.subject.lower().startswith("re:"):
        subject = "Re: %s" % subject
    _send_email(request, mlist, subject, form.cleaned_data["message"], {
                    "In-Reply-To": "<%s>" % message.message_id,
                    "References": "<%s>" % message.message_id,
                })
    return HttpResponse("The reply has been sent successfully.",
                        mimetype="text/plain")
Ejemplo n.º 38
0
def reply_view(request, pk_forum, pk_thread):
    forum = get_object(Forum.objects.active(), pk=pk_forum)
    category = forum.category
    threads = forum.threads.active()
    thread = get_object(threads, pk=pk_thread)
    form = ReplyForm(request.POST or None)
    editor_name = MARKUP_EDITORS[MARKUP]
    editor_style = 'js/forum/markitup/sets/%s/style.css' % editor_name
    editor_set = 'js/forum/markitup/sets/%s/set.js' % editor_name

    if form.is_bound and form.is_valid():
        new_reply = form.save(request.user.forum_profile, forum, thread)
        return redirect(new_reply)

    return render(request, 'forum/reply.html', {
        'category': category,
        'forum': forum,
        'thread': thread,
        'form': form,
        'editor_name': editor_name,
        'editor_style': editor_style,
        'editor_set': editor_set,
    })
Ejemplo n.º 39
0
def post(request, post_id):

    comment_form = CommentForm()
    reply_form = ReplyForm()
    try:
        post = Post.objects.get(id=post_id)
        tags = Tag.objects.filter(tag_posts__id=post_id)
        categories = Category.objects.all()
        if post:
            comments = Comment.objects.filter(comment_post__id=post_id)
            reg_form = UserRegForm()
            likes = len(Like.objects.filter(like_post__id=post_id))
            dislikes = len(Dislike.objects.filter(dislike_post__id=post_id))
            forbidden_words = Forbidden.objects.all()
            comments_replies = []

            if comments:
                for comment in comments:  ## check comments for forbidden words
                    for forbidden_word in forbidden_words:
                        comment.comment_text = comment.comment_text.replace(
                            forbidden_word.word,
                            ("*" * len(forbidden_word.word)))
                    replies = Reply.objects.filter(
                        reply_comment__id=comment.id)
                    comments_replies.append(replies)

                if replies:

                    for reply in replies:  ## check replies for forbidden words
                        for forbidden_word in forbidden_words:
                            reply.reply_text = reply.reply_text.replace(
                                forbidden_word.word,
                                ("*" * len(forbidden_word.word)))

            context = {
                'post': post,
                'categories': categories,
                'comments': comments,
                'replies': comments_replies,
                'comment_form': comment_form,
                'reply_form': reply_form,
                'likes': likes,
                'dislikes': dislikes,
                'tags': tags,
            }

    except Post.DoesNotExist:
        raise Http404("Post does not exist")

    return render(request, 'post.html', context)
Ejemplo n.º 40
0
 def post(self):
     if not self.has_permission:
         return
     page = int(self.get_argument('page', 1))
     topic_id = int(self.get_argument('topic_id', 0))
     topic = Topic.get(id=topic_id)
     if not topic_id:
         result = {'status': 'error', 'message':
             '无此主题,不能创建评论'}
         if self.is_ajax:
             return self.write(result)
         else:
             self.flash_message(result)
             return self.redirect_next_url()
     user = self.current_user
     form = ReplyForm(self.request.arguments)
     if form.validate():
         reply = form.save(user=user, topic=topic)
         if 'class="mention"' in reply.content:
             put_notifier(reply)
         result = {'status': 'success', 'message': '评论创建成功',
                 'content': reply.content, 'name': reply.author.name,
                 'nickname': reply.author.nickname, 'author_avatar':
                 reply.author.get_avatar(size=48), 'author_url':
                 reply.author.url, 'author_name': reply.author.name,
                 'author_nickname': reply.author.nickname,
                 'reply_url': reply.url, 'created': reply.created,
                 'id': reply.id, 'floor': reply.floor}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(topic.url)
     if self.is_ajax:
         return self.write(form.result)
     self.flash_message(form.result)
     return self.render("topic/index.html", form=form, topic=topic,
             category='index', page=page)
Ejemplo n.º 41
0
    def post(self):
        page = int(self.get_argument('page', 1))
        category = self.get_argument('category', 'index')
        topic_id = int(self.get_argument('topic_id', 0))
        topic = Topic.get(id=topic_id)
        if not topic_id:
            result = {'status': 'error', 'message': '无此主题,不能创建评论'}
            if self.is_ajax:
                return self.write(result)
            else:
                self.flash_message(**result)
                return self.redirect_next_url()
        user = self.current_user
        form = ReplyForm(self.request.arguments)
        if form.validate():
            reply = form.save(user=user, topic=topic)
            reply.put_notifier()
            result = {'status': 'success', 'message': '评论创建成功',
                      'content': reply.content, 'name': reply.author.name,
                      'nickname': reply.author.nickname, 'author_avatar':
                      reply.author.get_avatar(size=48), 'author_url':
                      reply.author.url, 'author_name': reply.author.name,
                      'author_nickname': reply.author.nickname,
                      'reply_url': reply.url, 'created': reply.created,
                      'id': reply.id, 'floor': reply.floor}
            if self.is_ajax:
                return self.write(result)
            self.flash_message(**result)
            return self.redirect(topic.url)

        reply_count = topic.reply_count
        page_count = (reply_count + config.reply_paged - 1) // config.reply_paged
        replies = topic.get_replies(page=page, category=category)
        data = dict(form=form, topic=topic, replies=replies, category=category, page=page, page_count=page_count,
                    url=topic.url)
        return self.send_result_and_render(form.result, "topic/index.html", data)
Ejemplo n.º 42
0
def reply(request, topic_id):
    if request.method == 'POST':
        form = ReplyForm(request.POST)
        if form.is_valid():
            reply = form.save(commit=False)
            reply.topic_id = topic_id
            reply.save()
            topic = Topic.objects.get(id=topic_id)
            topic.reply_date = timezone.now()
            topic.save()
            return redirect("/")
    else:
        form = ReplyForm()
        return render_to_response('form.html',{'form': form}, context_instance=RequestContext(request))
Ejemplo n.º 43
0
def client(request):
    """
    Render the client homepage.
    Grabs what is needed for the client: their projects / bids, notifications, and any questions
    on their projects
    """
    if request.method == "POST":
        # User submitted a project, add this project to the database
        form = ProjectSubmissionForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data["name"]
            requirements = form.cleaned_data["requirements"]
            keywords = form.cleaned_data["keywords"]
            description = form.cleaned_data["description"]

            new_project = Project(name=name,
                                  requirements=requirements,
                                  keywords=keywords,
                                  description=description,
                                  client=request.user,
                                  is_approved=False)

            new_project.save()
        else:
            blank_form = LoginForm()
            return render(request, "client.html", { "invalid": True, "form": blank_form })
    form = ProjectSubmissionForm()
    reply_form = ReplyForm()
    bids = Bid.objects.filter(project__client__id=request.user.id)
    projects = Project.objects.filter(client_id=request.user.id)
    questions = Question.objects.filter(project__client__id=request.user.id)
    notifications = Notification.objects.filter(recipient__id=request.user.id)
    context = {
            "bids": bids,
            "form": form,
            "projects": projects,
            "questions": questions,
            "reply_form": reply_form,
            "notifications": notifications
    }
    return render(request, "client.html", context)
Ejemplo n.º 44
0
def index(request, mlist_fqdn, message_id_hash):
    '''
    Displays a single message identified by its message_id_hash (derived from
    message_id)
    '''
    store = get_store(request)
    message = store.get_message_by_hash_from_list(mlist_fqdn, message_id_hash)
    if message is None:
        raise Http404
    message.sender_email = message.sender_email.strip()
    set_message_votes(message, request.user)
    mlist = store.get_list(mlist_fqdn)

    context = {
        'mlist': mlist,
        'message': message,
        'message_id_hash': message_id_hash,
        'months_list': get_months(store, mlist.name),
        'reply_form': ReplyForm(),
    }
    return render(request, "message.html", context)
Ejemplo n.º 45
0
def post_body_view(request, school_name, post_id, post_type):
    form_msg = {}
    ctx = {}
    print post_type

    if request.method == 'POST':
        user = request.user
        ip = get_ip_address(request)
        post = get_post_by_id(post_id)
        if post_type == "reply":
            post_form_kwargs = {
                "user": user, "post": post,
                "ip": ip}

            form = ReplyForm(
                request.POST, **post_form_kwargs)
        else:
            reply_id = request.POST['reply_id']
            print reply_id
            post_form_kwargs = {
                "user": user, "ip": ip,
                "reply_id": reply_id}

            form = CommentForm(
                request.POST, **post_form_kwargs)

        if form.is_valid():
            print form.cleaned_data
            form.save()

            if post_type == "reply":
                context = Context({'replys': [form.reply], 'commentForm': CommentForm()})
                return_str = render_block_to_string(
                    'discussion/post-body.html', 'replys', context)
            else:
                return_str = {
                    "reply_id": form.reply_id,
                    "comment": form.comment.comment_body}

            form_msg['message'] = return_str
        else:
            form_msg['errors'] = form.errors

        print form_msg
        json_ctx = json.dumps(form_msg)
        return HttpResponse(json_ctx, mimetype='application/json')

    else:
        replyForm = ReplyForm()
        commentForm = CommentForm()
        post = get_post_by_id(post_id)
        reply = get_post_reply(post_id)

        ctx = {
            "school_name": school_name,
            "post": post,
            "replys": reply,
            "commentForm": commentForm,
            "replyForm": replyForm}

    return render_to_response(
        'discussion/post-body.html', ctx,
        context_instance=RequestContext(request))
Ejemplo n.º 46
0
def add_reply(request):
    form = ReplyForm(request.POST)
    if form.is_valid():
        reply = form.save(commit=False)
        review = request.POST.get('review')
        user_rep = request.POST.get('user')
        r1 = reply.rate_objective
        r2 = reply.rate_complete

        repute_rev = User_Reputation.objects.get(user=user_rep)

        reputation = User_Reputation.objects.filter(user=request.user)

        if reputation:
            r = User_Reputation.objects.get(user=request.user)
            repute = r.reputation
            entity_alpha = r.entity_alpha
            entity_beta = r.entity_beta
        else:
            r = User_Reputation()
            r.user = request.user
            r.reputation = 0.5
            r.entity_alpha = 0.5
            r.entity_beta = 0.5
            r.votes = 0

            entity_alpha = 0.5
            entity_beta = 0.5
            repute = 0.5

            r.save()

#r3 = ((r1+r2)/2) * repute/1000

        alpha = ((r1 + r2) / 2)

        beta = 1 - alpha
        entity_alpha += alpha
        entity_beta += beta
        entity_reputation = (entity_alpha / (entity_alpha + entity_beta))

        r4 = repute_rev.reputation

        if r4 == 1:
            repute_rev.reputation = r4
            repute_rev.entity_alpha = entity_alpha
            repute_rev.entity_beta = entity_beta
            repute_rev.save()

        else:
            repute_rev.reputation = (r4 + entity_reputation) / 2
            repute_rev.entity_alpha = entity_alpha
            repute_rev.entity_beta = entity_beta
            repute_rev.save()

        review = ProductReview.objects.get(id=review)
        reply.review = review
        reply.user = request.user

        reply.save()

        template = "pdcts/reply_review.html"
        html = render_to_string(template, {'reply': reply})
        response = simplejson.dumps({'success': 'True', 'html': html})

    else:
        html = form.errors.as_ul()
        response = simplejson.dumps({'success': 'False', 'html': html})
    return HttpResponse(response,
                        content_type='application/javascript; charset=utf-8')
Ejemplo n.º 47
0
def thread_index(request, mlist_fqdn, threadid, month=None, year=None):
    ''' Displays all the email for a given thread identifier '''
    search_form = SearchForm(auto_id=False)
    store = get_store(request)
    thread = store.get_thread(mlist_fqdn, threadid)
    if not thread:
        raise Http404
    prev_thread, next_thread = store.get_thread_neighbors(mlist_fqdn, threadid)

    sort_mode = request.GET.get("sort", "thread")
    set_message_votes(thread.starting_email, request.user)

    from_url = reverse("thread",
                       kwargs={
                           "mlist_fqdn": mlist_fqdn,
                           "threadid": threadid
                       })
    # Tags
    tag_form = AddTagForm(initial={'from_url': from_url})
    try:
        tags = Tag.objects.filter(threadid=threadid, list_address=mlist_fqdn)
    except Tag.DoesNotExist:
        tags = []

    # Favorites
    fav_action = "add"
    if request.user.is_authenticated():
        try:
            Favorite.objects.get(list_address=mlist_fqdn,
                                 threadid=threadid,
                                 user=request.user)
        except Favorite.DoesNotExist:
            pass
        else:
            fav_action = "rm"

    # Extract relative dates
    today = datetime.date.today()
    days_old = today - thread.starting_email.date.date()
    days_inactive = today - thread.last_email.date.date()

    mlist = store.get_list(mlist_fqdn)
    subject = stripped_subject(mlist, thread.starting_email.subject)

    # TODO: eventually move to a middleware ?
    # http://djangosnippets.org/snippets/1865/
    is_bot = True
    user_agent = request.META.get('HTTP_USER_AGENT', None)
    if user_agent:
        is_bot = robot_detection.is_robot(user_agent)

    context = {
        'mlist': mlist,
        'threadid': threadid,
        'subject': subject,
        'tags': tags,
        'search_form': search_form,
        'addtag_form': tag_form,
        'month': thread.date_active,
        'first_mail': thread.starting_email,
        'neighbors': (prev_thread, next_thread),
        'months_list': get_months(store, mlist.name),
        'days_inactive': days_inactive.days,
        'days_old': days_old.days,
        'sort_mode': sort_mode,
        'fav_action': fav_action,
        'reply_form': ReplyForm(),
        'is_bot': is_bot,
        'participants': thread.participants,
    }
    context["participants"].sort(key=lambda x: x[0].lower())

    if is_bot:
        # Don't rely on AJAX to load the replies
        context["replies"] = _get_thread_replies(request, thread)

    return render(request, "thread.html", context)
Ejemplo n.º 48
0
def add_reply(request):
    form = ReplyForm(request.POST)
    if form.is_valid():
        reply = form.save(commit=False)
        review = request.POST.get('review')
        user_rep = request.POST.get('user')
	r1 = reply.rate_objective
	r2 = reply.rate_complete

	repute_rev = User_Reputation.objects.get(user = user_rep)

	reputation = User_Reputation.objects.filter(user = request.user)

	if reputation:
		r = User_Reputation.objects.get(user = request.user)
		repute = r.reputation
		entity_alpha = r.entity_alpha
		entity_beta =  r.entity_beta
	else:
		r = User_Reputation()
		r.user = request.user
		r.reputation = 0.5
		r.entity_alpha = 0.5
		r.entity_beta =  0.5
		r.votes = 0

		entity_alpha = 0.5
		entity_beta = 0.5
		repute = 0.5

		r.save()

	#r3 = ((r1+r2)/2) * repute/1000

	alpha = ((r1+r2)/2)

        beta = 1 - alpha
        entity_alpha += alpha
        entity_beta += beta
	entity_reputation = (entity_alpha/(entity_alpha + entity_beta))


	r4 = repute_rev.reputation

	if r4 == 1:
		repute_rev.reputation = r4
		repute_rev.entity_alpha = entity_alpha
		repute_rev.entity_beta = entity_beta
	 	repute_rev.save()

	else:
		repute_rev.reputation = (r4 + entity_reputation)/2
		repute_rev.entity_alpha = entity_alpha
		repute_rev.entity_beta = entity_beta
	 	repute_rev.save()

        review = ProductReview.objects.get(id=review)
	reply.review = review
        reply.user = request.user
	
	reply.save()
    
        template = "pdcts/reply_review.html"
        html = render_to_string(template, {'reply': reply })
        response = simplejson.dumps({'success':'True', 'html': html})
        
    else:
        html = form.errors.as_ul()
        response = simplejson.dumps({'success':'False', 'html': html})
    return HttpResponse(response, content_type='application/javascript; charset=utf-8')