Ejemplo n.º 1
0
def addDiagnoseComment():
    form = CommentsForm(request.form)
    resultForm=form.validate()
    if resultForm.status==rs.SUCCESS.status:
        #session['remember_me'] = form.remember_me.data
        # login and validate the user...
        diagnoseComment=Comment(form.userId,form.receiverId,form.diagnoseId,form.content)
        db_session.add(diagnoseComment)
        db_session.commit()
        db_session.flush()
        score=constant.DiagnoseScore[form.score]
        diagnose=Diagnose.getDiagnoseById(form.diagnoseId)
        diagnose.score=form.score
        Diagnose.save(diagnose)
        #为医生添加一些冗余字段
        if hasattr(diagnose,'doctor'):
            doctor=diagnose.doctor
            if score!=0:
                if doctor.goodFeedbackCount:
                    doctor.goodFeedbackCount+=1
                else:
                    doctor.goodFeedbackCount=1
            if doctor.feedbackCount:
                doctor.feedbackCount+=1
            else:
                doctor.feedbackCount=1
            Doctor.save(doctor)
        #flash('成功添加诊断评论')
        return jsonify(rs.SUCCESS.__dict__)
    return jsonify(rs.FAILURE.__dict__)
Ejemplo n.º 2
0
def add_comment(trail_id):
    user = flask_login.current_user
    profile = Hiker.objects.get({'_id': user.id})
    current_trail = Trails.objects.get({'_id': ObjectId(trail_id)})
    form = CommentsForm()
    if form.validate_on_submit():
        # sightings = request.form.getlist('sightings')
        # this line makes test_comments.py work
        sightings = [objects['tag'] for objects in form.sightings.data]
        comment = Comment(
            author=profile,
            date_comment=datetime.datetime.now(),
            body=form.body.data,
            sightings=sightings,
            date_started=form.date_started.data,
            ratings=form.ratings.data,
            hours_taken=form.hours_taken.data,
            minutes_taken=form.minutes_taken.data
        )
        current_trail.comments.append(comment)
        comment_date = comment.date_comment.strftime("%b, %d %Y, %H:%M")
        try:
            current_trail.save()
            flash(f"New comments by '{comment}', on '{comment_date}'"
                  f'have been added.',
                  'teal')
            return redirect(url_for('get_trail', trail_id=trail_id))
        except ValidationError as ve:
            current_trail.comments.pop()
            print(ve)
            print(ve.message)
            flash(ve, 'deep-orange darken-3')
    return render_template('trails/new_comments.template.html', form=form,
                           current_trail=current_trail)
Ejemplo n.º 3
0
def addDiagnoseComment():
    form = CommentsForm(request.form)
    resultForm = form.validate()
    if resultForm.status == rs.SUCCESS.status:
        #session['remember_me'] = form.remember_me.data
        # login and validate the user...
        diagnoseComment = Comment(form.userId, form.receiverId,
                                  form.diagnoseId, form.content)
        db_session.add(diagnoseComment)
        db_session.commit()
        db_session.flush()
        score = constant.DiagnoseScore[form.score]
        diagnose = Diagnose.getDiagnoseById(form.diagnoseId)
        diagnose.score = form.score
        Diagnose.save(diagnose)
        #为医生添加一些冗余字段
        if hasattr(diagnose, 'doctor'):
            doctor = diagnose.doctor
            if score != 0:
                if doctor.goodFeedbackCount:
                    doctor.goodFeedbackCount += 1
                else:
                    doctor.goodFeedbackCount = 1
            if doctor.feedbackCount:
                doctor.feedbackCount += 1
            else:
                doctor.feedbackCount = 1
            Doctor.save(doctor)
        #flash('成功添加诊断评论')
        return jsonify(rs.SUCCESS.__dict__)
    return jsonify(rs.FAILURE.__dict__)
Ejemplo n.º 4
0
def page(request, id):
    p = get_object_or_404(App_new, pk=id)
    form_comment=CommentsForm()
    com = Comments.objects.filter(page=p)

    if request.method=="POST":
        form_comment = CommentsForm(request.POST)
        if form_comment.is_valid():
            Comments.objects.create(**{'comment_content':request.POST.get('comment_content'),
                                       'comment_author':request.POST.get('comment_author'), 'page': p})
            return HttpResponseRedirect('/')
    return render(request, 'apppshka/page.html', {'page': p, 'form_comment':form_comment, 'comments':com})
Ejemplo n.º 5
0
def discussion_page(id):
    #POSSIBLE BUG HERE
    form = CommentsForm(request.form)
    # Create cursor
    c, conn = connection()

    # select current article page that was clicked
    c.execute("SELECT * FROM articles WHERE id = %s", [id])

    article = c.fetchone()

    # article title is need so you can put inside comment table
    current_title = article['title']

    # Fetch all comments for html page
    c.execute("SELECT * FROM comments WHERE article_title=%s AND common_id=%s",
              [current_title, id])

    # fetch all into variable for later use
    comments = c.fetchall()

    # if post means comment is being added
    if request.method == 'POST' and form.validate():
        # get form body data as this is post method and create cursor dont need if post as this is post already at the top
        # THIS IS RETURNING AN EMPTY STRING WHY~~~~ answer: compare login html input and discussion html render field
        new_comment = form.comment.data

        # Create Cursor
        c, conn = connection()

        # Execute query
        c.execute(
            "INSERT INTO comments(article_title, comment, author, common_id) VALUES(%s, %s, %s, %s)",
            (current_title, new_comment, session['username'], id))

        # Commit to DB
        conn.commit()

        # Close connection
        c.close()
        conn.close()

        flash('Comment added!', 'success')
        return redirect(url_for('discussion_page', id=id))

    return render_template('discussion.html',
                           article=article,
                           form=form,
                           comments=comments)
Ejemplo n.º 6
0
def view(id):
    if request.method == "GET":
        info = blogs.get(blogs.c.id == id)
        form = CommentsForm()
        comment = comments.filter(comments.c.blog_id == id)
        return {'form':form, 'info':info, 'comment':comment}

    if request.method == "POST":
        form = CommentsForm()
        flag = form.validate(request.params)
        if flag:
            info = comments(**form.data)
            info.blog_id = id
            info.save()
        return redirect('/view/%s' % id)
Ejemplo n.º 7
0
def show_post(post_id):
    requested_post = BlogPost.query.get(post_id)
    all_comments = Comments.query.filter_by(blog_id=post_id).all()
    c_form = CommentsForm()
    if request.method == 'POST':
        if current_user.is_authenticated:
            new_comment = Comments(user_comments=c_form.comments.data,
                                   blog_comment=requested_post,
                                   the_user_comment=current_user)
            db.session.add(new_comment)
            db.session.commit()
            return redirect(url_for('show_post', post_id=post_id))
        else:
            flash('You need to login to register a comment')
            return redirect(url_for('login'))
    else:
        all_blog_comments = {}
        for c in all_comments:
            commenting_user = Users.query.get(c.user_id)
            all_blog_comments[c.user_comments] = commenting_user
        print(all_blog_comments)

        return render_template("post.html",
                               post=requested_post,
                               form=c_form,
                               all_comments=all_blog_comments)
Ejemplo n.º 8
0
def index():
    from models import Articles, Comments
    from forms import ArticlesForm, CommentsForm

    if request.method == 'POST':
        print(request.form)
        us_form = ArticlesForm(request.form)

        if us_form.validate():
            post_art = Articles(**us_form.data)
            db.session.add(post_art)
            db.session.commit()

            return 'Article was created'
        else:
            us_form = CommentsForm(request.form)

            if us_form.validate():
                post_com = Comments(**us_form.data)
                db.session.add(post_com)
                db.session.commit()
                return 'Commit was created'
            else:
                raise Exception
    if request.method == 'GET':
        vie_posts = Articles.query.all()
        return render_template('home.txt', posts=vie_posts)
Ejemplo n.º 9
0
def edit_comment(id):
    # Create Cursor
    c, conn = connection()

    # Get comment by id
    c.execute("SELECT * FROM comments WHERE id = %s", [id])

    # represents all rows of 1 comment of given id
    comment = c.fetchone()

    # Get form
    form = CommentsForm(request.form)

    # Populate comment form fields
    form.comment.data = comment['comment']

    # Before Post check if author of comment is the one editing
    comment_author = comment['author']
    # this variable is made so the redirect can be directed to correct article id
    comment_common_id = comment['common_id']
    if session['username'] == comment_author:
        pass
    else:
        flash('Cannot edit must be appropriate author', 'danger')
        return redirect(url_for('discussion_page', id=comment_common_id))

    if request.method == 'POST' and form.validate():
        new_comment = request.form['comment']

        # Execute
        c.execute("UPDATE comments SET comment=%s WHERE id = %s",
                  (new_comment, id))

        # Commit to DB
        conn.commit()

        # Close connection
        c.close()
        conn.close()

        flash('Comment Updated', 'success')

        return redirect(url_for('discussion_page', id=comment_common_id))

    return render_template('edit_comment.html', form=form, comment=comment)
Ejemplo n.º 10
0
def submit_comments(request):
    print "submitting comments..."
    if request.method == "POST":
        comments_form = CommentsForm(data=request.POST)
        next_url = request.POST.get("next_url", "/")
        if comments_form.is_valid():
            comments_form.save()
            # user_id = request.user.user_id
            # group_id =
            # cursor = connection.cursor()
            # cursor.execute('''INSERT INTO make_comment () values()''')
            print "comments_form is valid!"
            return redirect(next_url)
        else:
            print "comments_form is not valid!"
            return redirect('/')
    print "request type is not POST!"
    return redirect('/')
Ejemplo n.º 11
0
def edit_comment(trail_id, n):
    user = flask_login.current_user
    current_trail = Trails.objects.get({'_id': ObjectId(trail_id)})
    comment_to_edit = current_trail.comments[n]
    trail_name = current_trail.trail_name
    if comment_to_edit.author._id != user.id:
        error_msg = "You're not authorized to edit this comment"
        flash(error_msg, 'deep-orange darken-3')
        return redirect(url_for('get_trail', trail_id=trail_id))
    form = CommentsForm(obj=comment_to_edit)
    if form.validate_on_submit():
        sightings = [objects['tag'] for objects in form.sightings.data]
        try:
            Trails.objects.raw({'_id': ObjectId(trail_id)}).update(
                {"$set": {
                    "comments."+str(n)+".date_comment":
                    datetime.datetime.now(),
                    "comments."+str(n)+".body": form.body.data,
                    "comments."+str(n)+".sightings": sightings,
                    "comments."+str(n)+".date_started":
                    datetime.datetime.combine(form.date_started.data,
                                              datetime.time()),
                    "comments."+str(n)+".ratings": form.ratings.data,
                    "comments."+str(n)+".hours_taken": form.hours_taken.data,
                    "comments."+str(n)+".minutes_taken":
                    form.minutes_taken.data
                }
                })
            comment_date = datetime.datetime.now().strftime("%b, %d %Y, %H:%M")
            flash("Comments have been editted by"
                  f"'{comment_to_edit.author}', on '{comment_date}'.", 'teal')
        except ValidationError as ve:
            current_trail.comments.pop()
            comment_errors = ve.message['comments'][-1]
            flash(comment_errors, 'deep-orange darken-3')
        return redirect(url_for('get_trail', trail_id=trail_id))
    return render_template('trails/edit_comments.template.html', form=form,
                           comment=comment_to_edit, n=n, trail_id=trail_id,
                           trailName=trail_name)
Ejemplo n.º 12
0
def get_recipe_database(id):
    """Return recipe Information--ingredients,nutritional data, directions etc"""

    recipe = Recipe.query.get(id)
    comment_form = CommentsForm()
    if not recipe:
        flash(f"Recipe Not Found...")
        return redirect('/')
    if comment_form.validate_on_submit() and CURR_USER_KEY in session:
        comment = Comment(comment=comment_form.comment.data,
                          user_id=g.user.id,
                          recipe_id=id)
        db.session.add(comment)
        db.session.commit()
        return redirect(f'/api/get-recipe-database/{id}')
    comments = recipe.comments
    users, times = u_util.get_users(recipe)
    avg_rate = r_util.calculate_average_rating(id, recipe.average_rate)
    user_rating = rec_util.is_empty_query(id)
    percentages = r_util.calculate_percentages_stars(id)
    nutrients, vitamins = rec_util.get_nutrients_recipe(
        recipe, recipe.servings)
    nutrients = n_util.sort_nutrients(nutrients)
    fats, carbs, no_daily = n_util.get_fats_carbs()
    calories = math.ceil(recipe.calories / recipe.servings)
    return render_template("/recipes/recipe-check.html",
                           recipe=recipe,
                           nutrients=nutrients,
                           vitamins=vitamins,
                           fats=fats,
                           carbs=carbs,
                           calories=calories,
                           no_daily=no_daily,
                           user_rating=user_rating,
                           percentages=percentages,
                           comment_form=comment_form,
                           comments=comments,
                           users=users,
                           times=times)
Ejemplo n.º 13
0
def post_detail_view(request, year, month, day, post):
    post = get_object_or_404(Post,
                             slug=post,
                             status='published',
                             publish__year=year,
                             publish__month=month,
                             publish__day=day)
    comments = post.comments.filter(active=True)
    csubmit = False
    e_form = None
    email = None
    name = None
    logged_user = None
    user = request.user
    if request.user.is_authenticated():
        logged_user = request.user.username
        name = request.user.first_name
        email = request.user.email
    if request.method == 'POST':
        form = CommentsForm(request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.name = logged_user
            new_comment.email = email
            new_comment.post = post
            new_comment.save()
            csubmit = True
            e_form = CommentsForm()
    else:
        form = CommentsForm()
    return render(
        request, 'BlogApp/post_detail.html', {
            'post': post,
            'form': form,
            'csubmit': csubmit,
            'comments': comments,
            'e_form': e_form,
            'logged_user': logged_user,
            'name': name
        })