Example #1
0
 def post(self, request, *args, **kwargs):
     form = CommentForm(request.POST)
     comments = Comment.objects.all().order_by("-created")
     if form.is_valid():
         form.save()
         messages.add_message(request, messages.INFO, 'Kommentar tilføjet.')
     return redirect('guests')
Example #2
0
def CreateComment (request):
    if request.method=="POST":
    # comment has been added
        form = CommentForm(data=request.POST)
        if form.is_valid():
            #print("valid")
            parent_obj = None
            # get parent comment id from hidden input
            try:
                # id integer e.g. 15
                parent_id = int(request.POST.get('parent_id'))
            except:
                parent_id = None
            # if parent_id has been submitted get parent_obj id
            if parent_id:
                parent_obj = Comment.objects.get(id=parent_id)
                # if parent object exist
                if parent_obj:
                    # create replay comment object
                    replay_comment = form.save(commit=False)
                    # assign parent_obj to replay comment
                    replay_comment.parent = parent_obj
            # normal comment
            # create comment object but do not save to database
            new_comment = form.save(commit=False)
            new_comment.save()
            messages.success(request, 'your comment has been recieved waiting for confirmation') 
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
        else:
            messages.error(request, 'problem setting your comment') 
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Example #3
0
def edit_comment(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    context = get_view_context(request)

    if not request.user.is_authenticated:
        return redirect_to_login(request.get_full_path())
    elif request.user != comment.user:
        raise PermissionDenied

    if request.method == 'POST':
        form = CommentForm(request.POST, instance=comment)
        context['commentform'] = form

        if form.is_valid():
            form.save()
            context['obj'] = comment
            context['is_parent'] = True
            # child comment
            if comment.parent:
                context['is_parent'] = False
            return render(request, 'comment/content.html', context)
    else:
        form = CommentForm(instance=comment)
        context['commentform'] = form
        context["comment"] = comment
        return render(request, 'comment/update_comment.html', context)
Example #4
0
 def post(self, request, *args, **kwargs):
     form = CommentForm(request.POST, instance=self.comment)
     context = self.get_context_data()
     if form.is_valid():
         form.save()
         context['comment'] = self.comment
         return render(request, 'comment/comments/comment_content.html', context)
Example #5
0
def book_detail(request, pk):
    template_name = 'book_detail.html'
    book = get_object_or_404(Book, pk=pk)

    comments = book.comment_set.all()

    # Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        comment_form.instance.book = book
        reply_id = request.POST.get('comment_id')
        if reply_id:
            comment_qs = Comment.objects.get(id=reply_id)
            comment_form.instance.reply = comment_qs
        comment_form.instance.author = request.user
        if comment_form.is_valid():
            comment_form.save()
            messages.success(request, f'评论已提交,核审通过后展示。')
            return redirect(f'/detail/{pk}')

    else:
        comment_form = CommentForm()

    return render(request, template_name, {
        'books': book,
        'comments': comments,
        'comment_form': comment_form
    })
Example #6
0
def comment_create(request):

    full_name = request.POST.get("full_name")
    phone_number = request.POST.get("phone_number")
    email_address = request.POST.get("email")

    restaurant_id = request.POST.get("restaurant")
    content = request.POST.get("content")

    data = {
        "full_name": full_name,
        "phone_number": phone_number,
        "email": email_address,
        "content": content,
        "restaurant": restaurant_id
    }

    form = CommentForm(data=data)
    if form.is_valid():
        form.save()
        # messages.success(request, "Your comment has been sent.")
    else:
        messages.error(request, "Your comment has not been sent.")

    return redirect("restaurant:pre_order_confirm", pk=restaurant_id)
Example #7
0
 def post(self, request, *args, **kwargs):
     form = CommentForm(request.POST, instance=self.comment, request=self.request)
     context = self.get_context_data()
     if form.is_valid():
         form.save()
         context['comment'] = self.comment
         self.data = render_to_string('comment/comments/comment_content.html', context, request=self.request)
         return UTF8JsonResponse(self.json())
Example #8
0
def comment_create(request):
    recipe_id = request.POST.get('recipe')
    content = request.POST.get('content')
    data = {'content': content, 'recipe': recipe_id}
    form = CommentForm(data=data)
    if form.is_valid():
        form.save()
        messages.success(request, 'コメントを投稿しました。')
    else:
        messages.error(request, 'コメントが投稿できませんでした。')
    return redirect('recipe:detail', pk=recipe_id)
Example #9
0
def photo(request, idph):
    '''

    :param request:
    :param idph:
    :return:
    '''
    if request.session.get('member_id', None):
        photo_owner_user = Images.objects.get(pk=int(idph))
        activ_user = InstaUser.objects.get(pk=request.session['member_id'])
        if Likes.objects.filter(picture=photo_owner_user,
                                sender_id=activ_user).exists():
            text_button = "Мне больше не нравится"
        else:
            text_button = "Мне нравится"
        like_len = len(Likes.objects.filter(picture=photo_owner_user))
        form = CommentForm(request.POST or None,
                           request.FILES or None,
                           initial={
                               "publication_id": photo_owner_user.id,
                               "date":
                               timezone.now() - datetime.timedelta(days=1),
                               "sender_id": activ_user.id,
                           })
        form.fields['sender_id'].widget = forms.HiddenInput()
        form.fields['publication_id'].widget = forms.HiddenInput()
        form.fields['date'].widget = forms.HiddenInput()
        if request.method == "POST" and form.is_valid():
            form.save()
        create = InstaUser.objects.get(
            pk=photo_owner_user.created_by.id).nickname_user
        send_user = InstaUser.objects.get(pk=photo_owner_user.created_by.id).id
        context = {
            'id': photo_owner_user.id,
            'created_by': create,
            'created_id': send_user,
            'created_at': photo_owner_user.created_at,
            'image_id': photo_owner_user.image_id.url,
            'form': form,
            'l_num': like_len,
            'text_button': text_button,
        }
        try:
            com = Comments.objects.filter(
                publication_id=photo_owner_user.id)  #[:5]
            context['comments'] = com
        except Comments.DoesNotExist:
            pass

        return render(request, 'image/photo.html', context)
    else:
        return HttpResponse("Чтобы посмотреть фото, зайдите на сайт")
Example #10
0
def comment_create(request):
    recipe_id = request.POST.get("recipe")
    content = request.POST.get("content")

    data = {"content": content, "recipe": recipe_id}

    form = CommentForm(data=data)
    if form.is_valid():
        form.save()
        messages.success(request, "コメントを投稿しました。")
    else:
        messages.error(request, "コメントが投稿できませんでした")

    return redirect("recipe:detail", pk=recipe_id)
Example #11
0
    def post(self, request, *args, **kwargs):
        comment_form = CommentForm(request.POST)
        target = request.POST.get('target')
        target_type = target.split('/')[1]
        temp = None
        if target_type == 'post':
            target_id = target.split('/')[-1].split('.')[0]
            temp = Post.objects.get(id=target_id).title # 获取文章标题
        if target_type == 'links':
            temp = '友链页面'

        if comment_form.is_valid():
            instance = comment_form.save(commit=False)
            instance.target = temp
            instance.save()
            succeed = True
            return redirect(target)
        else:
            succeed = False
        target = temp
        context = {
            'succeed': succeed,
            'form': comment_form,
            'target': target
        }
        return self.render_to_response(context=context)
Example #12
0
def detail(request):
    post_id = request.GET.get('post', 1)
    post = Post.objects.get(id = post_id)
    comment_form = CommentForm()
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        'markdown.extensions.toc',
        TocExtension(slugify=slugify)
    ])
    post.content = md.convert(post.content)
    post.toc = md.toc
    post.save()
    post.view_times()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            comment_list = Comment.objects.filter(post=post)
            return render(request, 'blog/page.html',
                          context={'post': post, 'comment_list': comment_list, 'comment_form': comment_form})
    else:
        comment_list = Comment.objects.filter(post=post)
        return render(request, 'blog/page.html', context = {'post': post,'comment_list':comment_list,'comment_form':comment_form})
Example #13
0
def post_comment(request):
    if request.method == 'POST':

        if request.POST.get('action') == 'delete':
            id = request.POST.get('nodeid')
            c = Comment.objects.get(id=id)
            c.delete()
            return JsonResponse({'remove': id})

        else:

            post_id = request.POST.get('post_id')
            post = Post.objects.get(id=post_id)

            comment_form = CommentForm(request.POST)
            if comment_form.is_valid():

                node_id = request.POST.get('nodeid')

                user_comment = comment_form.save(commit=False)
                result = comment_form.cleaned_data.get('content')

                user = request.user.username
                user_comment.post = post
                user_comment.name = request.user
                user_comment.save()
                node_id = user_comment.id

                return JsonResponse({
                    'result': result,
                    'user': user,
                    'node_id': node_id
                })
Example #14
0
def discuss(request, category_id=None):
    if category_id:
        get_object_or_404(Category.objects.visible(), pk=category_id)

    user = request.user

    if request.method == 'POST':
        form = TopicForm(user=user, data=request.POST)
        com_form = CommentForm(user=user, data=request.POST)

        if (all([form.is_valid(), com_form.is_valid()])
                and not request.is_limited()):
            if not user.u.update_post_hash(form.get_topic_hash()):
                return redirect(
                    request.POST.get('next', None)
                    or form.get_category().get_absolute_url())

            # wrap in transaction.atomic? inspired by spirit
            topic = form.save()
            com_form.topic = topic
            comment = com_form.save()
            comment_posted(comment=comment, mentions=com_form.mentions)
            return redirect(topic.get_absolute_url())
    else:
        form = TopicForm(user=request.user, initial={'category': category_id})
        com_form = CommentForm()

    context = {'form': form, 'com_form': com_form}

    template = 'topic/discuss.html'
    return render(request, template, context)
Example #15
0
def ReviewDetail(request, username, imdb_id):
    user_comment = request.user
    user = get_object_or_404(User, username=username)
    movie = Movie.objects.get(imdbID=imdb_id)
    review = Review.objects.get(user=user, movie=movie)

    comments = Comment.objects.filter(review=review).order_by('date')

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.review = review
            comment.user = user_comment
            comment.save()
            return HttpResponseRedirect(
                reverse('user-review', args=[username, imdb_id]))
    else:
        form = CommentForm()

    context = {
        'review': review,
        'movie': movie,
        'comments': comments,
        'form': form,
    }

    template = loader.get_template('movie_review.html')

    return HttpResponse(template.render(context, request))
Example #16
0
    def post(self, request, *args, **kwargs):
        print(request.POST)
        comment_form = CommentForm(request.POST)
        #comment_form = CommentForm({'nickname':'jerry','website':'https://www.cnblogs.com/hjy123/p/12957489.html','email':'shen@com','content':'写好了写好了写好了写好了写好了写好了写好了'})
        #print(comment_form)
        # print(comment_form.data.get('nickname'))
        # print(comment_form.data.get('website'))
        # print(comment_form.data.get('email'))
        # print(comment_form.data.get('content'))
        target = request.POST.get('target')

        if comment_form.is_valid():
            instance = comment_form.save(commit=False)
            instance.target = target
            instance.save()
            succeed = True
            return redirect(target)
        else:
            succeed = False

        context = {
            'succeed': succeed,
            'form': comment_form,
            'target': target,
        }
        return self.render_to_response(context)
Example #17
0
def post_detail(request, topic=None, id=None):
    instance = get_object_or_404(Post, id=id)
    username = request.user
    if instance.draft:
        if not instance.author == username:
            raise Http404

    logged_in = False
    if request.user.is_authenticated:
        logged_in = True

    comments = instance.comment.all()
    form = CommentForm(request.POST or None)
    if form.is_valid():
        new_comment = form.save(commit=False)
        new_comment.author = request.user
        new_comment.post = Post.objects.get(pk=id)
        new_comment.save()

    context = {
        "title": instance.title,
        "instance": instance,
        "username": username,
        "comments": comments,
        "logged_in": logged_in,
        "form": form
    }
    return render(request, "posts/post_detail.html", context)
Example #18
0
    def post(self, request, *args, **kwargs):
        obj = self.get_object()
        if obj is not None:
            form = CommentForm(request.POST or None)
            if form.is_valid():
                s = form.save(commit=False)
                s.article = obj

                try:
                    s.added_by = request.user
                    logger.info("article {} commented by {}".format(
                        obj, s.added_by))

                except Exception as e:
                    logger.warning("{}".format(e))
                    logger.info("login called")
                    return redirect('login')

                s.save()
                return HttpResponseRedirect(f'/blog/{obj.id}')
            c = Comment.objects.filter(article=obj).order_by('-id')
            self.context['object'] = obj
            self.context['comments'] = c
            self.context['form'] = form

        return render(request, self.template_name, self.context)
Example #19
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)
    new_comment = None
    #Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            # create comment object but dont save to database yet
            new_comment = comment_form.save(commit=False)
            #Assign the current post to the comment
            new_comment.post = post
            # Save the comment to the database
            new_comment.save()
            # return redirect('blog:post_detail_view')

    else:
        comment_form = CommentForm()

    return render(
        request, 'blog/post/bloger.html', {
            'post': post,
            'comments': comments,
            'comment_form': comment_form,
            'new_comment': new_comment
        })
Example #20
0
def PostDetails(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    user = request.user
    profile = Profile.objects.get(user=user)
    comment = Comment.objects.filter(post=post).order_by('date')

    if request.user.is_authenticated:
        profile = Profile.objects.get(user=user)
        # For the color of the favorite button

        if profile.favorites.filter(id=post_id).exists():
            favorited = True

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.user = user
            comment.save()

            return HttpResponseRedirect(reverse('post:postdetails', args=[post_id]))
    else:
        form = CommentForm()
    template = loader.get_template('post_detail.html')

    context = {
        'post': post,
        'comment': comment,
        'form': form,
        'profile': profile,
    }

    return HttpResponse(template.render(context, request))
Example #21
0
 def post(self, request, *args, **kwargs):
     album = get_object_or_404(Album, uuid=kwargs.get("uuid"))
     comment_form = CommentForm(request.POST)
     if comment_form.is_valid():
         comment = comment_form.save(commit=False)
         comment.album = album
         comment.save()
     return self.get(request, *args, **kwargs)
Example #22
0
def post_detail(request, pk):
    try:
        post = get_object_or_404(Post, pk=pk)
    except:
        return render(request, 'home/doesnotexist.html', {})

    user = request.user

    if not post.ispublished and user != post.author:
        return render(request, 'home/doesnotexist.html', {})

    if user.is_authenticated:
        try:
            postinfo = PostInfo.objects.filter(user=user).get(post=post)
        except:
            PostInfo.objects.create(user=user, post=post)
            postinfo = PostInfo.objects.filter(user=user).get(post=post)

        if request.method == "POST":
            form = CommentForm(request.POST)
            if form.is_valid():
                comment = form.save(commit=False)
                comment.author = user
                comment.post = post
                comment.created_date = timezone.now()
                comment.save()
            else:
                return render(request, 'home/invalidform.html', {})

        form = CommentForm()

        comments = Comment.objects.filter(post=post)

        comments.order_by('created_date')

        context = {
            'post': post,
            'postinfo': postinfo,
            'comments': comments,
            'form': form
        }

    else:
        comments = Comment.objects.filter(post=post)

        comments.order_by('created_date')

        context = {
            'post': post,
            'postinfo': None,
            'comments': comments,
            'form': None
        }

        context['topics'] = Topic.objects.filter(post=post)

    return render(request, 'blog/post_detail.html', context)
Example #23
0
def comment_create(request, id=None):
    data = dict()
    article = Article.objects.get(id=id)
    form = CommentForm()
    now = time.time()

    if request.session.get(
            'pause', False) and request.session.get('start_time', False) > now:
        messages.error(request,
                       _('Ви вже залишили коментар, зачекайте хвилину.'),
                       extra_tags='error')

    else:
        if request.is_ajax() and request.method == 'POST':
            form = CommentForm(request.POST)

            if form.is_valid() and request.user.is_authenticated():
                comment = form.save(commit=False)
                comment.comments_article = article
                comment.comments_user = Profile.objects.get(
                    pk=request.user.pk
                )  # АБО comment.comments_from = auth.get_user(request)  АБО comment.comments_from_id = auth.get_user(request).id
                comment.save()

                form = CommentForm()

                messages.success(request,
                                 _('Коментар добавлений успішно!'),
                                 extra_tags='success')

                request.session['pause'] = True
                request.session['start_time'] = time.time() + 20

                comments = article.comments.all().order_by('-comments_create')
                current_page = Paginator(comments, 4)
                page_number = request.GET.get('page', 1)
                data['html_comments'] = render_to_string(
                    'partial_comments_list.html',
                    {"comments": current_page.page(page_number)},
                    request=request)

                data['form_is_valid'] = True

            else:
                data['form_is_valid'] = False

    message = messages.get_messages(request)
    if message:
        data['html_messages'] = render_to_string('messages.html',
                                                 {'messages': message},
                                                 request=request)

    context = {'form': form, 'article': article}
    data['html_form'] = render_to_string('partial_comment_form.html',
                                         context,
                                         request=request)
    return JsonResponse(data)
Example #24
0
def new_comment(request):
    if request.method == 'POST':
        post = Post.objects.get(pk=request.POST.get('post_id'))
        form = CommentForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.target = post
            instance.save()
            return redirect(reverse('post-detail', kwargs={'post_id':
                                                           post.id}))
def home_screen_view(request):
    context = {}
    # questions = Question.objects.all()
    # context['questions'] = questions
    user = request.user
    query = ''
    if request.GET:
        query = request.GET.get('q', '')
        context['query'] = str(query)

    blog_posts = sorted(get_blog_queryset(query),
                        key=attrgetter('date_updated'),
                        reverse=True)

    #Pagination
    page = request.GET.get('page', 1)
    blog_posts_paginator = Paginator(blog_posts, BLOG_POSTS_PER_PAGE)
    try:
        blog_posts = blog_posts_paginator.page(page)
    except PageNotAnInteger:
        blog_posts = blog_posts_paginator.page(BLOG_POSTS_PER_PAGE)
    except EmptyPage:
        blog_posts = blog_posts_paginator.page(blog_posts_paginator.num_pages)

    context['blog_posts'] = blog_posts

    if request.POST:
        form_comment = CommentForm(request.POST or None)
        if form_comment.is_valid():
            #context['comment_success'] = request.POST['blog_post']
            comment_obj = form_comment.save(commit=False)
            author = Account.objects.filter(email=user.email).first()
            comment_obj.author = author
            comment_obj.save()
            comment_obj = CommentForm()
        if request.POST['like_status']:
            form_like = LikeForm(request.POST or None)
            like_obj = form_like.save(commit=False)
            author = Account.objects.filter(email=user.email).first()
            like_obj.author = author
            like_obj.save()
            like_obj = LikeForm()

            context['success_like'] = "success_like"

    # if request.is_ajax():
    #     body_unicode = request.body.decode('utf-8')
    #     body = json.loads(body_unicode)
    #     like_status = body['like_status']
    #     context['like_status'] = like_status

    comment_ = Comment.objects.all()
    context['comments'] = comment_

    return render(request, './home.html', context)
Example #26
0
 def test_save_anonymous_user(self):
     data = {
         'body': self.body,
         'post': self.post.id,
         'guest_name': self.guest_name}
     form = CommentForm(data=data)
     self.assertTrue(form.is_valid())
     comment = form.save()
     self.assertEqual(comment.body, self.body)
     self.assertEqual(comment.post, self.post)
     self.assertEqual(comment.guest_name, self.guest_name)
     self.assertLessEqual(comment.created_at, timezone.now())
def add_comment(request, question_id):
    post = get_object_or_404(Question, pk=question_id)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('poll:detail', question_id)
    else:
        form = CommentForm()
    return render(request, 'comment/add_comment.html', {'form': form})
Example #28
0
def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.user = request.user
            comment.save()
            return redirect('comment:single', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'comment/comment_form.html', {'form': form})
Example #29
0
 def post(self, request, *args, **kwargs):
     comment_form = CommentForm(request.POST)
     target = request.POST.get('target')
     if comment_form.is_valid():
         instance = comment_form.save(commit=False)
         instance.target = target
         instance.save()
         succeed = True
         return redirect(target)
     else:
         succeed = False
     context = {'succeed': succeed, 'form': comment_form, 'target': target}
     return self.render_to_response(context)
Example #30
0
def post_detail(request, slug=None):
    post = get_object_or_404(CategorySeries, series_slug=slug)
    form = CommentForm(request.POST or None)

    if form.is_valid():
        comment_form = form.save(commit=False)
        comment_form.post = post
        comment_form.save()

        return HttpResponseRedirect(post.get_absolute_url())

    context = {'posts': post, 'comment_form': form}
    return render(request, 'post/post_detail.html', context)
Example #31
0
def PostDetails(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    user = request.user
    profile = Profile.objects.get(user=user)
    MLP = Post.objects.all().order_by('-likes')[:5]
    favorited = False

    posts_count = Post.objects.filter(user=user).count()
    following_count = Follow.objects.filter(follower=user).count()
    followers_count = Follow.objects.filter(following=user).count()
    follow_status = Follow.objects.filter(following=user,
                                          follower=request.user).exists()

    #comment
    comments = Comment.objects.filter(post=post).order_by('date')

    if request.user.is_authenticated:
        profile = Profile.objects.get(user=user)
        #For the color of the favorite button

        if profile.favorites.filter(id=post_id).exists():
            favorited = True

    #Comments Form
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.user = user
            comment.save()
            return HttpResponseRedirect(reverse('postdetails', args=[post_id]))
    else:
        form = CommentForm()

    template = loader.get_template('post_detail.html')

    context = {
        'post': post,
        'favorited': favorited,
        'profile': profile,
        'form': form,
        'comments': comments,
        'posts_count': posts_count,
        'following_count': following_count,
        'followers_count': followers_count,
        'follow_status': follow_status,
        "MLP": MLP
    }

    return HttpResponse(template.render(context, request))
Example #32
0
def add_comment(request, post_id):
    post_id = int(post_id)
    post = get_object_or_404(Post, pk=post_id)
    context = { 'post': post, 'categories': Category.objects.all() }
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
        comment = comment_form.save()
        comment.owner = request.user
        comment.save()
        post.comment_set.add(comment)
        return redirect('post:get', post_id=post.pk)
    else:
        context['form'] = comment_form
        return render(request, 'post.html', context)
Example #33
0
def comment_create(request, id=None):
    data = dict()
    article = Article.objects.get(id=id)
    form = CommentForm()
    now = time.time()

    if request.session.get('pause', False) and request.session.get('start_time', False) > now:
        messages.error(request, _('Ви вже залишили коментар, зачекайте хвилину.'), extra_tags='error')

    else:
        if request.is_ajax() and request.method == 'POST':
            form = CommentForm(request.POST)

            if form.is_valid() and request.user.is_authenticated():
                comment = form.save(commit=False)
                comment.comments_article = article
                comment.comments_user = Profile.objects.get(pk=request.user.pk)                            # АБО comment.comments_from = auth.get_user(request)  АБО comment.comments_from_id = auth.get_user(request).id
                comment.save()

                form = CommentForm()

                messages.success(request, _('Коментар добавлений успішно!'), extra_tags='success')

                request.session['pause'] = True
                request.session['start_time'] = time.time() + 20

                comments = article.comments.all().order_by('-comments_create')
                current_page = Paginator(comments, 4)
                page_number = request.GET.get('page', 1)
                data['html_comments'] = render_to_string('partial_comments_list.html',
                                                         {"comments": current_page.page(page_number)},
                                                         request=request)

                data['form_is_valid'] = True

            else:
                data['form_is_valid'] = False

    message = messages.get_messages(request)
    if message:
        data['html_messages'] = render_to_string('messages.html',
                                                 {'messages': message},
                                                 request=request)

    context = {'form': form,
               'article': article}
    data['html_form'] = render_to_string('partial_comment_form.html',
                                         context,
                                         request=request)
    return JsonResponse(data)
Example #34
0
def detail_view(request, poi_id):
    comment_form = CommentForm(request.POST or None)
    poi = Poi.objects.get(id=poi_id)
    if comment_form.is_valid():
        comment = comment_form.save(commit=False)
        comment.poi = poi
        comment.save()
        return HttpResponseRedirect("/detail/%i" % poi.pk)
    return render_to_response(
        "misto.html",
        context_instance=RequestContext(
            request,
            {"poi": poi, "comment_form": comment_form, "comment_list": Comment.objects.filter(poi=poi).order_by("pk")},
        ),
    )
Example #35
0
def add_comment(request, post_id):
    """
    Process add comment post request
    """
    if request.method == 'POST':
        form = CommentForm(request.user, request.POST)
        if form.is_valid():
            # get post object with id
            post = Post.objects.get(id=post_id)

            # set comment user, post instance and parent (comment type)
            form.instance.user = request.user
            form.instance.post = post
            form.instance.parent = post

            # insert comment
            comment = form.save()

            # if user is auth. approve comment directly and fill user data
            if request.user.is_authenticated():
                # approve comment
                comment.approve()

                # fill user fullname, email data and save
                comment.fullname = "%s %s" %(request.user.first_name,
                                             request.user.last_name)
                comment.email = request.user.email
                comment.save()
            # if user not auth. create and send activation key with email
            else:
               # create activation key 
                comment.activation_key = User.objects.make_random_password()
                comment.save()
                send_email_validation.delay(comment)

            # add success message            
            messages.success(request, _("Comment created succesfully."))

            # redirect to post detail page
            return redirect("post_detail", post_id=post_id)

        # if form is not valid render post detail for showing errors
        return detail(request, post_id, comment_form=form)
    else:
        return redirect("post_detail", post_id=post_id)
Example #36
0
def detail(request, slug):
    qs_article = Article.objects.filter(slug=slug)
    article = qs_article.get()
    qs_article.update(views=article.views+1)
    comment_form = CommentForm(request.POST or None)
    article.comments = article.comment_set.filter(author__user__is_active=True, parent_comment=None, hidden=False)
    
    if request.user.is_authenticated():
        reported_comments = Comment.objects.filter(report__reporter__user=request.user)
        
        if request.POST and comment_form.is_valid():
            comment = comment_form.save(commit=False)
            account = Account.objects.filter(user=request.user).get()
            comment.author = account
            comment.parent_article = article
            
            if 'parent_comment' in request.POST:
                comment.parent_comment = Comment.objects.filter(pk=request.POST['parent_comment']).get()
                
                comment.parent_comment.author.to_accounts.create(from_account=account,
                                                                 category="comment",
                                                                 subject="Comment reply from " + str(comment.author) + "...",
                                                                 body=comment.text + '\n\n<a href="' + reverse('article_detail', kwargs={'slug': article.slug}) + '#comments">Read more here...</a>')
                
                if comment.parent_comment.author.alerts_subscribe:
                    email = comment.parent_comment.author.user.email
                    subject = "You've received a message on blog.chancegraff.me..."
                    text_message = "Your account has received a new message on Chance Graff's blog. You may view this message after you've signed into your account by visiting this address:  http://blog.chancegraff.me/messages"
                    html_message = "Your account has received a new message on Chance Graff's blog. You may <a href='http://blog.chancegraff.me/messages'>view this message</a> after you've signed into your account."
                
                    msg = EmailMultiAlternatives(subject, text_message, 'Chance Graff <*****@*****.**>', [email])
                    msg.attach_alternative(html_message, "text/html")
                    msg.send()
            
            comment.total_score = 1
            comment.save()
            
            author_vote = Vote.objects.create(voter=account, comment=comment, value=1)
            
            return redirect('comment_saved',  slug=article.slug)
    else:
        reported_comments = None
        
    return render(request, 'article/detail.html', {'article': article, 'comment_form': comment_form, 'reported_comments': reported_comments,})
Example #37
0
def show_article(request, pk):
    article = get_object_or_404(Article, pk=pk)

    if request.method == 'GET':
        comment_form = CommentForm()
    else:
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.author = request.user
            comment.article = article

            #if comment_form.cleaned_data['parent_id'] == '':
            if request.POST['parent_id'] == '':
                # the root comment
                pass
            else:
                comment.parent = Comment.objects.get(id=request.POST['parent_id'])

            comment.save()

    comment_tree = Comment.objects.filter(article=article)

    return render(request, 'article/show_article.html', {'article':article, 'comment_form':comment_form, 'comment_tree':comment_tree})