Beispiel #1
0
def movie_detail(request, pk):
    context = {}
    movie = Movie.objects.get(pk=pk)
    context['movie'] = movie
    context['imdb'] = 'http://www.imdb.com/title/' + str(movie.imdb_id)
    context['form1'] = CommentForm()
    if request.method == 'POST':
        form1 = CommentForm(request.POST)
        context['form1'] = form1
        if form1.is_valid():
            print 'valid form1'
            print request.user
            if request.user.is_authenticated():
                print 'comment'
                new_comment = Comment()
                new_comment.is_response = False
                new_comment.text = form1.cleaned_data['text']
                new_comment.user = request.user
                new_comment.movie = movie
                new_comment.save()
                return HttpResponseRedirect('/movie_detail/%s' % pk)
            else:
                print 'anonymous user'
                return HttpResponseRedirect('/please_login/')

        else:
            print 'form1 not valid'
    else:
        print 'GET'
    return render_to_response('movie_detail.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #2
0
def movie_detail(request, pk):
    context = {}
    movie = Movie.objects.get(pk=pk)
    context['movie'] = movie
    context['imdb'] = 'http://www.imdb.com/title/' + str(movie.imdb_id)
    context['form1'] = CommentForm()
    if request.method == 'POST':
        form1 = CommentForm(request.POST)
        context['form1'] = form1
        if form1.is_valid():
            print 'valid form1'
            print request.user
            if request.user.is_authenticated():
                print 'comment'
                new_comment = Comment()
                new_comment.is_response = False
                new_comment.text = form1.cleaned_data['text']  
                new_comment.user = request.user
                new_comment.movie = movie
                new_comment.save()
                return HttpResponseRedirect('/movie_detail/%s' %pk )       
            else:  
                print 'anonymous user'
                return HttpResponseRedirect('/please_login/')
                
        else:
            print 'form1 not valid'
    else:
        print 'GET'
    return render_to_response('movie_detail.html', context, context_instance=RequestContext(request))
Beispiel #3
0
def show_detail(request, pk):
    context = {}
    show = Show.objects.get(pk=pk)
    context['form'] = CommentForm()
    context['show'] = show
    context['imdb'] = 'http://www.imdb.com/title/' + str(show.imdb_id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        context['form'] = form
        if form.is_valid():
            if request.user.is_anonymous:
                print 'anonymous user'
                return HttpResponseRedirect('/please_login/')
            else:
                new_comment = Comment()
                new_comment.text = form.cleaned_data['text']
                new_comment.user = request.user
                new_comment.show = show
                new_comment.save()
                return HttpResponseRedirect('/show_detail/%s' % pk)

        else:
            print 'form not valid'
    return render_to_response('show_detail.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #4
0
def episode_detail(request, pk):
    context = {}
    episode = Episode.objects.get(pk=pk)
    context['form'] = CommentForm()
    context['episode'] = episode
    context['imdb'] = 'http://www.imdb.com/title/' + str(episode.imdb_id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        context['form'] = form
        if form.is_valid():
            if request.user.is_authenticated:
                new_comment = Comment()
                new_comment.text = form.cleaned_data['text']
                new_comment.user = request.user
                new_comment.episode = episode
                new_comment.save()
            elif request.user.is_anonymous:
                print 'anonymous user'
                return HttpResponseRedirect('/please_login/')
            return HttpResponseRedirect('/episode_detail/%s' % pk)

        else:
            print 'form not valid'
    return render_to_response('episode_detail.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #5
0
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('Your comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / \
               current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    if page == 0:
        page = 1
    print(page)
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination)
Beispiel #6
0
 def post(self, request, *args, **kwargs):
     form = CommentForm(request.POST)
     if form.is_valid():
         comment = form.save(commit=False)
         comment.page = self.page
         comment.save()
     return HttpResponseRedirect(self.request.path_info)
Beispiel #7
0
def post(request):
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        new_comment = comment_form.save(commit=False)
        new_comment.user = request.user
        new_comment.post = my_models.Post.objects.get(
            id=request.GET.get("post_id"))
        new_comment.save()
        return redirect(request.get_full_path())
    else:
        article = get_object_or_404(my_models.Post,
                                    id=request.GET.get("post_id"))
        tags = my_models.Tag.objects.all()
        auth_count = User.objects.count()
        ix = randint(0, auth_count - 1)
        random_user = User.objects.all()[ix:ix + 1][0]
        comment_form = CommentForm()
        return render(
            request, 'main/post.html', {
                "article":
                article,
                'parts':
                my_models.Part.objects.all(),
                "tags":
                tags,
                "random_user":
                random_user,
                "comment_form":
                comment_form,
                "four_popular_posts":
                sorted(list(my_models.Post.objects.all()),
                       key=lambda x: x.comment.count(),
                       reverse=True)[0:4],
            })
Beispiel #8
0
def film(request, pk):
    film = get_object_or_404(Film, id=pk)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        form.instance.user = request.user
        form.instance.film = film
        form.save()
        return redirect(film)
    return render(request, 'main/film.html', {'film': film, "form": form})
Beispiel #9
0
    def on_message(self, message):
        comment_json = json.loads(message)

        form = CommentForm(data=comment_json)
        form.is_valid()     # TODO: raise exception if not valid

        comment = Comment(**form.clean())
        comment.save()

        # self.write_message(self.generate_comment_json())
        self.update_waiters()
def recipe_detail(request, pk):

    context = {}
    recipe = Recipe.objects.get(pk=pk)

    # Tabulate basic nutrition info
    tab = tabulate_basic_nutr(recipe)

    # Account for servings per recipe; round numbers; calc total mass
    sca = scale_basic_nutr(tab[0], tab[1], tab[2], tab[3], tab[4])

    # Save the total number of calories per serving to the database
    recipe.calories_tot = sca[2]['energy_tot']
    recipe.save()

    # Authenticate the user
    active = request.user.is_authenticated()

    # # Handle Comments
    old_comments = get_old_comments(recipe)
    if active:
        cntxt_comments_v = CommentForm(initial={'recipe': pk})
        if request.method == 'POST':
            from_form = CommentForm(request.POST)
            if from_form.is_valid():
                get_new_comments(from_form, request, old_comments, pk)
                return HttpResponseRedirect('/recipe_detail/%s/' % pk)

    # Context Variables
    context['recipe'] = recipe

    context['nutr_basic'] = sca[0]
    context['nutr_other'] = sca[1]
    context['energy_basic'] = sca[2]
    context['mass_basic'] = sca[3]

    context['nutr_individ'] = json.dumps(sca[4])

    # print  "%s" % json.dumps(sca[4])
    context['text_dict'] = json.dumps(sca[4])

    context['active'] = active

    context['rating_v'] = get_ratings(active, request, pk, recipe)
    context['rating_stat_v'] = get_rating_stats(recipe)

    context['old_comments_v'] = old_comments
    context['comments_v'] = cntxt_comments_v

    # Send data to template -----------------------------------------
    return render_to_response('recipe_detail.html', context,
                              context_instance=RequestContext(request))
Beispiel #11
0
def create_reply(reply_id):
    form = CommentForm()
    reply = Reply.query.get_or_404(reply_id)
    if request.method == 'POST' and form.validate_on_submit():
        comment = Comment(user=g.user,
                          content=form.content.data,
                          create_date=datetime.now(),
                          reply=reply)
        db.session.add(comment)
        db.session.commit()
        return redirect('{}#comment_{}'.format(
            url_for('post.detail', post_id=reply.post.id), comment.id))
    return render_template('comment/comment_form.html', form=form)
Beispiel #12
0
def add_comment_defect(request, defect_id):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            defect = Defect.objects.get(id=defect_id)
            comment_text = form.cleaned_data['comment_body']
            comment = Comment.objects.create(
                comment_body=comment_text,
                commenter=request.user,
                modified_date=datetime.datetime.now())
            comment.defect.add(defect)
            comment.save()
    return redirect('defect_by_id', defect_id)
Beispiel #13
0
def add_comment_test_session(request, test_session_id):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            test_session = TestSession.objects.get(id=test_session_id)
            comment_text = form.cleaned_data['comment_body']
            comment = Comment.objects.create(
                comment_body=comment_text,
                commenter=request.user,
                modified_date=datetime.datetime.now())
            comment.test_session.add(test_session)
            comment.save()
    return redirect('view_test_session', test_session_id)
Beispiel #14
0
def post(id):
    form = CommentForm()
    post = Post.query.filter_by(id=id).first_or_404()
    if form.validate_on_submit():
        comment = Comment(body=form.comment.data,
                          author=current_user,
                          source=post)
        db.session.add(comment)
        db.session.commit()
        flash('Comment successful.')
        return redirect(url_for('post', id=id))
    comments = post.comments
    return render_template('idpost.html',
                           post=post,
                           form=form,
                           comments=comments)
Beispiel #15
0
def mkcomment(request, pk, parent_comment=None):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['text']
            board = Board.objects.get(pk=pk)
            if parent_comment == None:
                comment = Comment.objects.create(user=request.user, board=board, text=text)
	    else:
                comment = Comment.objects.create(user=request.user, board=board, text=text, parent_comment=Comment.objects.get(pk=parent_comment))
        else:
            print "ERROR :::: "+str(form.errors)
    else:
        print "ERROR :::: HAHA LOLOLOLOLOL!!!!!!!"

    return HttpResponseRedirect('/board/'+pk)
Beispiel #16
0
def detail(request, pk):
    post = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post=post)

    form = CommentForm()
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post,
            )
            comment.save()

    context = {"post": post, "comments": comments, "form": form}
    return render(request, "main/detail.html", context)
Beispiel #17
0
def index(request):
    if request.method == 'GET':
        form = CommentForm()
        images = Image.objects.all().order_by('-id')[:3]

        comments = Comment.objects.all()
        return render(request, 'index.html', {
            'images': images,
            'comments': comments,
            'form': form
        })
    else:
        form = CommentForm(request.POST)

        form.instance.username = request.user.username
        form.instance.photo_id = request.POST['txt']

        if form.is_valid():

            form.save()

            return redirect('/')
        else:
            return HttpResponse(form
                                )
Beispiel #18
0
def index_2(request, pk):
    new = get_object_or_404(Posts, id=pk)
    comment = Comments.objects.filter(post=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            form.user = request.user
            form.post = new
            form.save()
            return redirect(index_2, pk)
    else:
        form = CommentForm()
    return render(request, 'main/index_2.html', {
        'new': new,
        'comment': comment,
        'form': form
    })
Beispiel #19
0
def post_comment(request):
    if request.POST and request.is_ajax():
        json_context = {'success': False, 'form_errors': []}

        form = CommentForm(request.POST)
        comment = form.save()
        if form.is_valid():
            json_context['success'] = 'Комментарий успешно добавлен!'
            json_context['commentHtml'] = render_to_string(
                'comments/post_comments.html', {
                    'nodes': [comment],
                    'can_post': True
                })
        else:
            json_context['form_errors'] = form.errors
        return HttpResponse(json.dumps(json_context),
                            content_type="application/json")
    return HttpResponseForbidden()
Beispiel #20
0
    def post(self, request, *args, **kwargs):

        author = request.POST['author']
        text = request.POST['text']
        parent_id = request.POST.get('parent', None)

        form = CommentForm({'author': author, 'text': text, 'parent': parent_id})
        form.is_valid()     # TODO: raise exception if invalid

        comment_data = form.clean()

        comment = Comment(**comment_data)
        comment.save()

        comment_list = self.get_comment_list()
        response_dict = {'comments': comment_list}

        return JsonResponse(response_dict, safe=False)
Beispiel #21
0
    def post(self, request, id):
        context = {}
        message = Message.objects.get(id=id)
        user = request.user

        if request.POST['type'] == 'comment':
            comments = Comment.objects.filter(
                message=message).order_by('-date_posted')
            context = {'comments': comments}
            form = CommentForm(request.POST)

            if form.is_valid:
                comment = form.save()
                context['comment'] = 'Youre comment has been saved'
                context['message'] = message
            else:
                context['comment'] = form.errors

            return render(request, 'message-detail.html', context)

        elif request.POST['type'] == 'edit':
            id = request.POST.get('id')

            if id:
                form = MessageForm(
                    request.POST, request.FILES, instance=message)

            if form.is_valid:
                message = form.save()
                context['text'] = "Your message has been saved"
                context['message'] = message
            else:
                context['text'] = form.errors

            return render(request, 'message-detail.html', context)

        elif request.POST['type'] == 'favorite':
            user.favorites.add(message)
            return HttpResponse(status=204)

        elif request.POST['type'] == 'unfavorite':
                user.favorites.remove(message)
                return HttpResponse(status=204)
Beispiel #22
0
def add_comment(request, blog_id):

    form = CommentForm(request.POST)
    article = get_object_or_404(Blog, id=blog_id)

    if form.is_valid():
        comment = BlogComment()
        comment.path = []
        comment.article_id = article
        comment.author_id = auth.get_user(request)
        comment.content = form.cleaned_data['comment_area']
        comment.save()
        try:
            comment.path.extend(BlogComment.objects.get(id=form.cleaned_data['parent_comment']).path)
            comment.path.append(comment.id)
        except ObjectDoesNotExist:
            comment.path.append(comment.id)
        comment.save()
    return HttpResponse("!")
Beispiel #23
0
    def post(self, *args, **kwargs):
        author = self.get_argument('author', None)
        text = self.get_argument('text', None)
        parent_id = self.get_argument('parentCommentId', None)

        form = CommentForm(data={
            'author': author,
            'text': text,
            'parent': parent_id
        })
        form.is_valid()     # TODO: raise exception if not valid

        comment = Comment(**form.clean())
        comment.save()

        response_dict = {'comments': get_comment_list()}
        comment_json = json.dumps(response_dict,
                                  cls=DjangoJSONEncoder)
        self.write(comment_json)
Beispiel #24
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     comments = self.page.comments.all()
     comment_form = CommentForm()
     context = {
         'comments': comments,
         'comment_form': comment_form,
         'title': self.page.title,
         'abstract': self.page.abstract
     }
     return context
Beispiel #25
0
def comment():
    form = CommentForm()
    page = request.url
    post_id = request.args.get('post_id')
    post = Post.query.filter_by(id=post_id).first_or_404()
    body = request.args.get('body')
    comments = Comment.query.filter_by(post_id=post_id).order_by(Comment.timestamp.desc()) 
    #comments = comments.query.order_by(comments.timestamp.desc())
    if form.validate_on_submit():
        language = guess_language(form.comment.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        comment = Comment(body=form.comment.data, author=current_user,
                    language=language, post_id=post_id)
        db.session.add(comment)
        db.session.commit()
        flash(_('Your comment is now live!'))
        return redirect(page) #(url_for('main.explore')) 
    return render_template('comment.html', title=_('Comment'),
           form=form, body=body, post=post, comments=comments)
Beispiel #26
0
def test_create_comment(django_user_model):
    user = django_user_model.objects.create(username='******')
    user.set_password('takeajacket')
    user.save()
    cult = Cult.objects.create(
        name='Sweet Dreams',
        slug='sweet-dreams',
        doctrine='Hold your head up, keep your head up!',
        city='Amsterdam',
    )
    event = Event.objects.create(
        cult=cult,
        title='SpaceX Falcon Heavy launch',
        slug='falcon-heavy-launch',
        details='Mars! Incoming!',
        date='2118-02-02',
        time='18:00',
        venue='SpaceX Fans HQ',
        address='2314 Olympus Str, 553 77',
        maps_url='https://goo.gl/maps/sample-link',
    )
    Membership.objects.create(
        cult=cult,
        user=user,
        role=Membership.LEADER,
    )
    form_data = {
        'body': 'Elon for president!',
    }
    form = CommentForm(data=form_data)
    assert form.is_valid()
    c = Client()
    logged_in = c.login(username='******', password='******')
    response = c.post('/' + cult.slug + '/' + event.slug + '/comment/',
                      form_data)
    assert logged_in
    assert response.status_code == 302
    assert Comment.objects.first()
    assert Comment.objects.first().body == form_data['body']
    assert Comment.objects.first().author == user
    assert Comment.objects.first().event == event
Beispiel #27
0
def get_article(news_id):
    article = Article.query.filter_by(id=news_id).first()
    form = CommentForm()
    if article is not None:
        with open(article.text) as file:
            text = file.read()
        if form.validate_on_submit():
            comment = Comment(author=form.name.data,
                              content=form.comment.data,
                              article_id=article.id)
            article.Comments.append(comment)
            db.session.add(comment)
            db.session.commit()
        return render_template('Article.html',
                               title=article.title,
                               article=article,
                               text=text,
                               form=form,
                               comments=article.Comments)
    else:
        abort(404, message='Article not found')
Beispiel #28
0
def show_defect(request, defect_id):
    context = dict()
    defect = Defect.objects.get(id=defect_id)
    context['defect'] = defect
    form = CommentForm()
    try:
        comments = Comment.objects.filter(defect=defect)
    except Comment.DoesNotExist:
        comments = None
    context['comments'] = comments
    context['form'] = form
    return render(request, "main/defect_details.html", context)
Beispiel #29
0
def view_test_session(request, test_session_id=None):
    context = dict()
    if test_session_id:
        session = TestSession.objects.get(id=test_session_id)
    form = CommentForm()
    try:
        comments = Comment.objects.filter(test_session=session)
    except Comment.DoesNotExist:
        comments = None
    context['test_session'] = session
    context['comments'] = comments
    context['form'] = form
    return render(request, "main/test_session.html", context)
Beispiel #30
0
def view_test_result(request, result_id=None):
    context = dict()
    if result_id:
        result = TestResult.objects.get(id=result_id)
    form = CommentForm()
    try:
        comments = Comment.objects.filter(test_result=result)
    except Comment.DoesNotExist:
        comments = None
    context['result'] = result
    context['comments'] = comments
    context['form'] = form
    return render(request, "main/test_result.html", context)
Beispiel #31
0
def mkcomment(request, pk, parent_comment=None):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['text']
            board = Board.objects.get(pk=pk)
            if parent_comment == None:
                comment = Comment.objects.create(user=request.user,
                                                 board=board,
                                                 text=text)
            else:
                comment = Comment.objects.create(
                    user=request.user,
                    board=board,
                    text=text,
                    parent_comment=Comment.objects.get(pk=parent_comment))
        else:
            print "ERROR :::: " + str(form.errors)
    else:
        print "ERROR :::: HAHA LOLOLOLOLOL!!!!!!!"

    return HttpResponseRedirect('/board/' + pk)
Beispiel #32
0
def board_url(request, pk):
    context = {}
    board = Board.objects.get(pk=pk)
    comments = Comment.objects.filter(board=board)

    context['board'] = board
    context['title'] = "Message Board"
    context['list'] = json.dumps(
        work_plz_v2(comments.filter(parent_comment=None)))
    context['comment_form'] = CommentForm()
    return render_to_response('board_page.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #33
0
def answer(qid, aid):
    answer = Answer.query.filter_by(id=aid).first_or_404()
    question = Question.query.filter_by(id=answer.answer_question.id).first_or_404()
    tags = question.tags.all()
    if (datetime.datetime.now()-question.created_at).days == 0:
        created_time = datetime.datetime.strftime(question.created_at, '%H:%M')
    else:
        created_time = datetime.datetime.strftime(question.created_at, '%Y-%m-%d')
    if (datetime.datetime.now()-answer.created_at).days == 0:
        answer_created_time = datetime.datetime.strftime(answer.created_at, '%H:%M')
    else:
        answer_created_time = datetime.datetime.strftime(answer.created_at, '%Y-%m-%d')
    form_question_comment = CommentForm(prefix="form_question_comment")
    if form_question_comment.validate_on_submit() and form_question_comment.submit.data:
        comment = Comment(content=form_question_comment.content.data)
        comment.comment_question = question
        author = User.query.filter_by(id=current_user.id).first()
        comment.comment_author = author
        db.session.add(comment)
        db.session.commit()
        flash('评论成功')
        return redirect(url_for('main.answer', qid=answer.answer_question.id, aid=answer.id))
    question_comments = question.question_comments
    form_answer_comment = CommentForm(prefix="form_answer_comment")
    if form_answer_comment.validate_on_submit() and form_answer_comment.submit.data:
        comment = Comment(content=form_answer_comment.content.data)
        comment.comment_answer = answer
        author = User.query.filter_by(id=current_user.id).first()
        comment.comment_author = author
        db.session.add(comment)
        db.session.commit()
        flash('评论成功')
        return redirect(url_for('main.answer', qid=answer.answer_question.id, aid=answer.id))
    answer_comments = answer.answer_comments
    return render_template('answer.html', question=question, answer=answer, tags=tags,
                           created_time=created_time, answer_created_time=answer_created_time,
                           form_question_comment=form_question_comment, question_comments=question_comments,
                           form_answer_comment=form_answer_comment, answer_comments=answer_comments)
Beispiel #34
0
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body=form.body.data,
                          post=post,
                          author=current_user._get_current_object())
        db.session.add(comment)
        flash('Your comment has been published.')
        return redirect(url_for('.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / \
               current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1
    if page == 0:
        page = 1
    print(page)
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    return render_template('post.html', posts=[post], form=form,
                           comments=comments, pagination=pagination)
Beispiel #35
0
def episode_detail(request, pk):
    context = {}
    episode = Episode.objects.get(pk=pk)
    context['form'] = CommentForm()
    context['episode'] = episode
    context['imdb'] = 'http://www.imdb.com/title/' + str(episode.imdb_id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        context['form'] = form
        if form.is_valid():
            if request.user.is_authenticated:
                new_comment = Comment()
                new_comment.text = form.cleaned_data['text']
                new_comment.user = request.user
                new_comment.episode = episode
                new_comment.save()
            elif request.user.is_anonymous:
                print 'anonymous user'
                return HttpResponseRedirect('/please_login/')
            return HttpResponseRedirect('/episode_detail/%s' %pk )
            
        else:
            print 'form not valid'
    return render_to_response('episode_detail.html', context, context_instance=RequestContext(request))
Beispiel #36
0
def question(id):
    question = Question.query.filter_by(id=id).first_or_404()
    tags = question.tags.all()
    if (datetime.datetime.now()-question.created_at).days == 0:
        created_time = datetime.datetime.strftime(question.created_at, '%H:%M')
    else:
        created_time = datetime.datetime.strftime(question.created_at, '%Y-%m-%d')
    form_question_comment = CommentForm(prefix="form_question_comment")
    if form_question_comment.validate_on_submit() and form_question_comment.submit.data:
        comment = Comment(content=form_question_comment.content.data)
        comment.comment_question = question
        author = User.query.filter_by(id=current_user.id).first()
        comment.comment_author = author
        db.session.add(comment)
        db.session.commit()
        flash('评论成功')
        return redirect(url_for('main.question', id=question.id))
    question_comments = question.question_comments
    form_add_answer = AddAnswerForm(prefix="form_add_answer")
    if form_add_answer.validate_on_submit() and form_add_answer.submit.data:
        ans = Answer(content=form_add_answer.content.data)
        ans.answer_question = question
        author = User.query.filter_by(id=current_user.id).first()
        ans.answer_author = author
        db.session.add(ans)
        db.session.commit()
        flash('回答成功')
        return redirect(url_for('main.question', id=question.id))
    answers = question.question_answers.all()
    for i in range(1,len(answers)):
        for j in range(0,len(answers)-i):
            if answers[j].users.count() < answers[j+1].users.count():
                answers[j],answers[j+1] = answers[j+1],answers[j]
    return render_template('question.html', question=question, tags=tags, created_time=created_time,
                               form_question_comment=form_question_comment, question_comments=question_comments,
                               form_add_answer=form_add_answer, answers=answers)
Beispiel #37
0
def show_detail(request, pk):
    context = {}
    show = Show.objects.get(pk=pk)
    context['form'] = CommentForm()
    context['show'] = show
    context['imdb'] = 'http://www.imdb.com/title/' + str(show.imdb_id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        context['form'] = form
        if form.is_valid():
            if request.user.is_anonymous:
                print 'anonymous user'
                return HttpResponseRedirect('/please_login/')
            else:
                new_comment = Comment()
                new_comment.text = form.cleaned_data['text']
                new_comment.user = request.user
                new_comment.show = show
                new_comment.save()
                return HttpResponseRedirect('/show_detail/%s' %pk )
            
        else:
            print 'form not valid'
    return render_to_response('show_detail.html', context, context_instance=RequestContext(request))
Beispiel #38
0
def add_comment_page(request, **kwargs):
    form = CommentForm()
    slug = kwargs['slug']
    post =Post.objects.get(slug=slug)
    if request.method == 'POST':
       
        form = CommentForm(request.POST)
        if form.is_valid:
            form.instance.post_id = post.id
            form.save(commit=True)
            messages.success(request,'Your comment has been submitted and will be visible after the site owner approves',extra_tags='alert')
            return HttpResponseRedirect(reverse('content',kwargs={'slug':slug}) + '#comments')
Beispiel #39
0
def modify_post(comment_id):
    comment = Comment.query.get_or_404(comment_id)
    if g.user != comment.user:
        flash('수정권한이 없습니다')
        return redirect(url_for('post.detail', post_id=comment.post.id))
    if request.method == 'POST':
        form = CommentForm()
        if form.validate_on_submit():
            form.populate_obj(comment)
            comment.modify_date = datetime.now()  # 수정일시 저장
            db.session.commit()
            return redirect('{}#comment_{}'.format(
                url_for('post.detail', post_id=comment.post.id), comment.id))
    else:
        form = CommentForm(obj=comment)
    return render_template('comment/comment_form.html', form=form)
Beispiel #40
0
def show_forum(request, course_name_slug, forum_name_slug):
    context_dict = {}

    try:
        course = Course.objects.get(slug=course_name_slug)
        forum = Forum.objects.get(slug=forum_name_slug)
        post_list = Post.objects.filter(forum=forum)
        post_form = PostForm()
        comment_form = CommentForm()

        comment_dict = {}

        current_user = request.user
        registered_account = check_user(current_user=current_user)

        if registered_account != 1 and registered_account != 2:
            is_user = False
        else:
            is_user = True

        if check_user(current_user=current_user) == 2:
            is_tutor = True
            print("tutor")
        else:
            is_tutor = False
            print("student")

        for post in post_list:
            comment_dict[post.id] = Comment.objects.filter(post=post)

        context_dict['course'] = course
        context_dict['forum'] = forum
        context_dict['posts'] = post_list
        context_dict['comment_dict'] = comment_dict
        context_dict['post_form'] = post_form
        context_dict['comment_form'] = comment_form
        context_dict['is_tutor'] = is_tutor
        context_dict['is_user'] = is_user

    except Forum.DoesNotExist:
        context_dict['forum'] = None
        context_dict['posts'] = None
        context_dict['comment_dict'] = None

    return render(request, 'main/forum.html', context=context_dict)
Beispiel #41
0
def showWorker(request):

    userAauthorized = request.user.is_authenticated

    if userAauthorized:
        refreshLastOnline(request.user)

    id = request.GET.get("id", None)

    if id == None:
        return render(request, 'errors/404.html', status=404)

    if userAauthorized != True:
        return render(request, 'errors/405.html', status=403)
    else:
        if request.method == "GET":

            commentForm = CommentForm()

        workerList = gerWorkList(user=request.user,
                                 idWorker=[id],
                                 userAauthorized=userAauthorized,
                                 its_superuser=request.user.is_superuser)
        comments = getComments(idWorker=id)

        if len(workerList) == 0:
            return render(request, 'errors/404.html', status=404)
        else:

            context = {}

            context["worker"] = workerList[0]
            context["commentForm"] = commentForm
            context["comments"] = comments
            context["userAauthorized"] = userAauthorized

            if userAauthorized:
                context['its_company'] = True if UserType.GetUserType(
                    request.user) == 2 else False
            else:
                context['its_company'] = False

            return render(request, 'Worker.html', context)
Beispiel #42
0
def post_details(request, post_list_id):
	try:
		latest_post = Post.objects.get(id=post_list_id)
	except Post.DoesNotExist:
		raise Http404("Post not found")
	if request.method == 'POST':
		form = CommentForm(request.POST)
		if form.is_valid():
			form.save()
			return redirect('/blog/'+str(post_list_id)+'/')
	else:
		form = CommentForm()
	context = {
		'latest_post': latest_post,
		'comments': latest_post.comments.all(),
		'form': form
	}
	return render(request, 'main/detail.html', context)
Beispiel #43
0
def RecipeDetailView(request, pk):

    context = {}

    recipe = Recipe.objects.get(pk=pk)
    context['recipe_v'] = recipe

    active = request.user.is_authenticated()
    context['active'] = active

    # Get vote_state ------------------------------------------------
    if active:
        h_temp = "_".join([str(pk), str(request.user.username)])
        vote, created = Vote.objects.get_or_create(recipe=recipe,
                                                   handle=h_temp)

        if created:
            return HttpResponseRedirect('/vote_stats_func/%s' % pk)

        context['vote_v'] = vote

    else:
        context['vote_v'] = 2

    # Get vote stats ------------------------------------------------
    vote_stat, created = VoteStat.objects.get_or_create(recipe=recipe)

    context['vote_stat_v'] = vote_stat

    # Retrieve old comments -----------------------------------------
    old_comments = Comment.objects.filter(recipe=recipe)
    context['old_comments_v'] = old_comments

    # Show empty form for new comments, process new comments --------
    if active:
        context['comments_v'] = CommentForm(initial={'recipe': pk})
        if request.method == 'POST':
            from_form = CommentForm(request.POST)

            if from_form.is_valid():
                new_comment = from_form.save()

                user_name = request.user.username
                time = str(new_comment.time_stamp)

                # Because comments might get moderated, a given comment-number
                # might not match the total number of allowed comments
                # preceding it (ie, if there are 10 comments, the next comment
                # will be #11 [ie, 10 + 1] but if #2 is deleted by the admin,
                # the subsequent comment should be #12 even though there are
                # only 11 comments in the list.
                length = len(old_comments)
                if length == 1:
                    number = length
                else:
                    number = old_comments[length - 2].number + 1

                new_comment.user_name = user_name
                new_comment.handle = "_".join([str(pk), user_name, time])
                new_comment.number = number
                new_comment.email = request.user.email
                new_comment.save()

                return HttpResponseRedirect('/recipe_detail/%s/' % pk)
            else:
                context['errors'] = new_comment.errors

    # Send data to template -----------------------------------------
    return render_to_response('recipe_detail.html', context,
                              context_instance=RequestContext(request))