def post(self, request, **kwargs):
     slug = self.kwargs['slug']
     article = Article.objects.filter(slug=slug).first()
     form = CommentForm(request.POST)
     if form.is_valid():
         c_type = form.cleaned_data.get('content_type')
         content_type = ContentType.objects.get(model=c_type)
         obj_id = form.cleaned_data.get('object_id')
         content_data = form.cleaned_data.get('content')
         parent_obj = None
         try:
             parent_id = int(request.POST.get('parent_id'))
         except:
             parent_id = None
         if parent_id:
             parent_qs = Comment.objects.filter(id=parent_id)
             if parent_qs.exists() and parent_qs.count() == 1:
                 parent_obj = parent_qs.first()
         new_comment, created = Comment.objects.get_or_create(
             user=request.user,
             content_type=content_type,
             object_id=obj_id,
             content=content_data,
             parent=parent_obj
         )
         return redirect('articles:detail', slug=article.slug)
Exemplo n.º 2
0
 def test_guest_name_has_to_be_present_for_anonymous_user(self):
     data = {
         'body': self.body,
         'post': self.post.id}
     form = CommentForm(data=data)
     self.assertFalse(form.is_valid())
     self.assertIn(_("This field is required."), form.errors['guest_name'])
Exemplo n.º 3
0
 def test_guest_name_is_not_required_for_logged_in_user(self):
     request = HttpRequest()
     request.user = self.AuthenticatedUser(
         username=self.faker.pronounceable_unique_id(length=30),
         password=self.faker.password(),
         email=self.faker.email())
     data = {
         'body': self.body,
         'post': self.post.id}
     form = CommentForm(data=data, request=request)
     self.assertTrue(form.is_valid())
Exemplo n.º 4
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())
Exemplo n.º 5
0
def comment(request,art_id):
    """保存评论"""
    if request.method == 'POST': 
        if not art_id:
            return HttpResponse("You commit wrong!")
        art = Articles.objects.get(id=int(art_id))
        form = CommentForm(request.POST)
        if form.is_valid():
            comm_body = form.cleaned_data['comm_body']
            Comment.objects.create(article_id=art,comm_body=comm_body)
            return HttpResponse("Thank you for you comment,It recoverd!")
        return HttpResponse("You don't commit anythings")
    elif request.method == 'GET':
        return HttpResponse("here")
Exemplo n.º 6
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)
Exemplo n.º 7
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)
Exemplo n.º 8
0
def comment(request, blog_id):
    """
    提交评论
    """
    blog = Blog.objects.get_by_id(blog_id)
    if blog is None:
        return Http404
    form = CommentForm(request.POST)
    if request.method == "POST":
        if form.is_valid():
            cmt = form.post(blog)
            cmt.ip = get_ip(request)
            cmt.save()
            return HttpResponseRedirect("/blog/%s#cmt" % blog.id)
    return render_and_response(request, "blog/detail.html", {"blog": blog, "form": form})
Exemplo n.º 9
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")},
        ),
    )
Exemplo n.º 10
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)
Exemplo n.º 11
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,})
Exemplo n.º 12
0
def PostDetails(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    user = request.user
    profile = Profile.objects.get(user=user)
    favorited = False

    #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,
    }

    return HttpResponse(template.render(context, request))
Exemplo n.º 13
0
def comment_add(request):

    comment=Comments.objects.all().order_by('-datetime')    



    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            name = cd['name']
            content = cd['content']
            subject = cd['subject']
            #datetime = cd['datetime']
            cmt=Comments(name=name,content=content,subject=subject,datetime=datetime.datetime.now())
            cmt.save()
            
            return HttpResponseRedirect('/comment/add/')
    else:
        form = CommentForm()
    return render_to_response('comment_add.html',
       {'form': form,'comment':comment}, context_instance=RequestContext(request))
Exemplo n.º 14
0
def blog_detail(request, slug):

    instance = get_object_or_404(Post, slug=slug)
    last_posts = Post.objects.all().order_by('-timestampt')[:5]
    share_string = quote(instance.content)

    #content_type = ContentType.objects.get_for_model(Post)
    comments = Comment.objects.filter_by_instance(instance)
    #Comment.objects.filter(post=instance)
    #instance.comments

    #content_type = ContentType.objects.get_for_model(instance.__class__)

    initial_data = {
        "object_id": instance.id,
        "content_type": 'post',
    }

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=True)
            print(comment)
    else:
        comment_form = CommentForm(initial=initial_data)

    #comments = instance.comment

    context = {
        "title": instance.title,
        "instance": instance,
        "share_string": share_string,
        "last_posts": last_posts,
        "comments": comments,
        "comment_form": comment_form,
    }

    return render(request, "post_detail.html", context)
Exemplo n.º 15
0
def blog_details(request, slug):
    welcome_page = WelcomePage.objects.get(id=1)
    categories = CategorySite.objects.all().filter(
        category__isnull=True).order_by('id')
    post_category = PostCategory.objects.all()
    post = Post.objects.get(slug=slug)
    content_type = post.get_content_type
    object_id = post.id
    comments = Comment.my_query.filter_by_instance(instance=post)

    if request.POST:
        form_comment = CommentForm(request.POST)
        if form_comment.is_valid():
            get_data = form_comment.cleaned_data.get('content')
            new_comment = Comment.objects.create(
                content_type=content_type,
                object_id=object_id,
                user=request.user,
                comment_type=CommentType.objects.get(id=1),
                content=get_data,
            )
            new_comment.save()
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    else:
        form_comment = CommentForm()

    context = {
        'post': post,
        'blog_detail': True,
        'categories': categories,
        'welcome_page': welcome_page,
        'post_cat': post_category,
        'comments': comments,
        'form_comment': form_comment,
    }
    context.update(csrf(request))

    return render(request, 'obaju/post.html', context)
Exemplo n.º 16
0
def post_detail(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    user = request.user

    comments = Comment.objects.filter(post=post).order_by('date')
    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_detail', args=[post_id]))
    else:
        form = CommentForm()

    return render(request,
                  'post/post_detail.html',
                  context={
                      'post': post,
                      'form': form,
                      'comments': comments
                  })
Exemplo n.º 17
0
    def post(self, request, *args, **kwargs):
        comment_form = CommentForm(request.POST)
        # exp: target='/post/12.html'
        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)
Exemplo n.º 18
0
def movie_comment(request,id,slug):
	movie = get_object_or_404(Movie,
						id=id,
						slug=slug)
	
	author = request.user
	new_comment =None
	if request.method=="POST":
		comment_form = CommentForm(data=request.POST)	
		if comment_form.is_valid():
			new_comment = comment_form.save(commit=False)
			new_comment.movie = movie
			new_comment.author = author 
			new_comment.save()
	else:
		comment_form = CommentForm()

	return render(request,
				'movies/movie/review.html',
				{'author':author,
				'movie':movie,
				'new_comment':new_comment,
				'comment_form':comment_form})
Exemplo n.º 19
0
def comment(request, aid):
    """
    评论处理
    :param request:
    :return:
    """
    article = Article.manager.all().filter(pk=aid).first()
    if request.method == "GET":
        form = CommentForm()
        article.read_count += 1
        return render(request, 'blog/single.html', context={'article': article, 'form': form})
    elif request.method == "POST":
        comment = CommentForm(request.POST)
        if comment.is_valid():
            comment = comment.save(commit=False)
            comment.user = User.manager.all().filter(account=request.session.get("account")).first()
            comment.article = Article.manager.all().filter(pk=aid).first()
            comment.article.comment_count += 1
            comment.article.save()
            comment.save()
            return redirect('/blog/single/%s' % aid)
        else:
            return HttpResponse("该页面不存在")
Exemplo n.º 20
0
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    user = request.user
    comments = Comment.objects.filter(post=post).order_by('-date')

    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.user = user
            comment.save()
            return redirect(reverse('post:post_detail', args=[pk]))
        else:
            return render(request, 'post_detail.html', {'comment_form': comment_form})
    else:
        comment_form = CommentForm()

    context = {'post': post,
               'comments': comments,
               'comment_form': comment_form,
               }
    return render(request, 'post_detail.html', context)
Exemplo n.º 21
0
def update_comment(request):
    comment_form = CommentForm(request.POST, user=request.user)

    if comment_form.is_valid():
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']
        comment.save()

        data = {
            'status': 'SUCCESS',
            'username': comment.user.username,
            'comment_time': comment.comment_time.strftime('%Y-%m-%d %H:%M:%S'),
            'text': comment.text,
        }
    else:
        data = {
            'status': 'ERROR',
            'message': list(comment_form.errors.values())[0][0]
        }

    return JsonResponse(data)
Exemplo n.º 22
0
def update_comment(request):
    referer = request.META.get('HTTP_REFERER', reverse('home'))
    comment_form = CommentForm(request.POST, user=request.user)
    data = {}

    if comment_form.is_valid():
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']

        parent = comment_form.cleaned_data['parent']
        if not parent is None:
            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()
        comment.send_mail()

        data['status'] = 'SUCCESS'
        data['username'] = comment.user.get_nickname_or_username()
        data['comment_time'] = comment.comment_time.timestamp()
        data['text'] = comment.text
        data['content_type'] = ContentType.objects.get_for_model(comment).model
        if not parent is None:
            data['reply_to'] = comment.reply_to.get_nickname_or_username()
        else:
            data['reply_to'] = ''
        data['pk'] = comment.pk
        data['root_pk'] = comment.root.pk if not comment.root is None else ''

    else:
        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
        # return render(request, 'error.html',{'message':comment_form.errors,'redirect_to':referer})

    return JsonResponse(data)
Exemplo n.º 23
0
def post_detail(request, id=None):
    instance = Post.objects.get(id=id)
    share_string = quote_plus(instance.content)
    initial_data = {
        "content_type": instance.get_content_type,
        "object_id": instance.id
    }
    form = CommentForm(request.POST or None, initial=initial_data)
    if form.is_valid():
        print('working')
        comment = form.save(commit=False)
        c_type = comment.content_type
        comment.content_type = ContentType.objects.get(model=c_type)
        parent_obj = None
        try:
            parent_id = int(request.POST.get("parent_id"))
        except:
            parent_id = None

        if parent_id:
            parent_qs = Comment.objects.filter(id=parent_id)
            if parent_qs.exists() and parent_qs.count() == 1:
                parent_obj = parent_qs.first()
        comment.parent = parent_obj
        new_comment = comment.save()
        return redirect('detail', id=instance.id)

    comments = instance.comments
    context = {
        'title': instance.title,
        'instance': instance,
        'share_string': share_string,
        'comments': comments,
        'comment_form': form,
    }
    template = 'post/detail.html'
    return render(request, template, context)
Exemplo n.º 24
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})
Exemplo n.º 25
0
    def post(self, request, *args, **kwargs):
        comment_form = CommentForm(request.POST)  # 接受form表单数据
        target = request.POST.get('target')

        if comment_form.is_valid():
            # 此处通过form表单对象创建了一个实例,不用再创建comment的对象了
            instance = comment_form.save(commit=False)
            instance.target = target
            instance.nickname = request.user.first_name
            instance.website = reverse('author', args=(request.user.id,))
            email = request.user.email
            instance.save()
            succeed = True
            return redirect(target)
        else:
            succeed = False
        context = {
            'succeed': succeed,
            # 若发生异常,form表单对象中会存入异常信息
            'form': comment_form,
            'target': target,
        }
        # 将数据渲染到响应对象和模板中
        return self.render_to_response(context)
Exemplo n.º 26
0
def addComment(request):
    if request.method == "POST":
        form_comment = CommentForm(data=request.POST)
        if form_comment.is_valid():
            comment = form_comment.save(commit=False)
            if request.user.is_authenticated:
                comment.user = request.user
            comment.save()
            subject = form_comment.cleaned_data['title']
            body = {
                'Username': '******' + str(request.user),
                'Fullname': 'Name:' + form_comment.cleaned_data['name'],
                'Email': 'From: ' + form_comment.cleaned_data['email'],
                'Message': 'Message: ' + form_comment.cleaned_data['content'],
            }
            message = "\n".join(body.values())
            try:
                send_mail(subject, message, '*****@*****.**', ['*****@*****.**'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')

        else:
            raise forms.ValidationError("wrong format")
    return render(request, 'home/index.html', {'commentForm': CommentForm()})
Exemplo n.º 27
0
def update_comment(request):
    referer = request.META.get('HTTP_REFERER', reverse('home'))
    comment_form = CommentForm(request.POST, user=request.user)
    data = dict()
    if comment_form.is_valid():
        # 通过验证,保存数据
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']

        parent = comment_form.cleaned_data['parent']
        if parent:
            comment.root = parent.root if parent.root else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()

        # 返回数据
        data['status'] = 'SUCCESS'
        data['username'] = comment.user.get_nickname_or_username()
        data['comment_time'] = comment.comment_time.strftime(
            '%Y-%m-%d  %H:%M:%S')
        data['text'] = comment.text
        if parent:
            data['reply_to'] = comment.reply_to.get_nickname_or_username()
        else:
            data['reply_to'] = ''
        data['id'] = comment.id
        data['root_id'] = comment.root.id if comment.root else ''

    else:
        # return render(request, 'error.html', {'message': comment_form.errors, 'referer': referer})
        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
Exemplo n.º 28
0
def comment_update(request):
    comment_form = CommentForm(request.POST, user=request.user)
    ajax_data = {}

    if comment_form.is_valid():
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['model_obj']

        # 判断是不是回复
        parent = comment_form.cleaned_data.get('parent', None)
        if parent is not None:
            comment.root = parent.root if parent.root is not None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()

        # 返回数据给前端ajax
        ajax_data['status'] = 'SUCCESS'
        ajax_data['username'] = comment.user.get_nickname_or_username()
        ajax_data['comment_time'] = comment.comment_time.strftime(
            '%Y-%m-%d %H:%M:%S')
        ajax_data['text'] = comment.text
        if parent is not None:
            ajax_data['reply_to'] = comment.reply_to.get_nickname_or_username()
        else:
            ajax_data['reply_to'] = ''
        ajax_data['pk'] = comment.pk
        ajax_data[
            'root_pk'] = comment.root.pk if comment.root is not None else ''

    else:
        ajax_data['status'] = 'ERROR'
        ajax_data['error_message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(ajax_data)
Exemplo n.º 29
0
def update_comment(request):
    '''
    #这是使用html表单验证的代码
    # 重定向操作,也就是说提交评论后应该还是在此评论页,但是数据做了更新
    referer = request.META.get('HTTP_REFERER', reverse('home'))

    #数据检查
    user = request.user
    if not user.is_authenticated:
        #redirect_to 是让错误页面可以有个返回的链接
        return render(request, 'error.html', {'message':'用户未登录', 'redirect_to':referer})

    text = request.POST.get('text', '').strip()   #去空格
    #要在后端做评论内容的判断,因为前端不论再怎么保障,都不可信
    if text == '':
        return render(request, 'error.html', {'message':'评论内容不能为空', 'redirect_to':referer})

    #用异常处理来判断评论对象到底有没有
    try:
        content_type = request.POST.get('content_type', '')
        object_id = int(request.POST.get('object_id', ''))  #因为从POST请求中获取的都是字符串类型,所以要通过int()转为数值类型

        #通过get方法获取到类型,但我们需要获取到大写的类名,所以再引用.model_class()
        #models_class 在此处可以认为是 BLog
        model_class = ContentType.objects.get(model=content_type).model_class()

        # 等价于blog = Blog.objects.get(pk=object_id),只不过我们写得更加通用,万一不是blog类型也可以使用
        model_obj = model_class.objects.get(pk=object_id)
    except Exception as e:
        return render(request, 'error.html', {'message':'评论对象不存在', 'redirect_to':referer})


    #检查通过,保存数据
    comment = Comment()
    comment.user = user
    comment.text = text
    comment.content_object = model_obj
    comment.save()

    return redirect(referer)
    '''
    '''
    这是使用django form表单的代码
    '''
    referer = request.META.get('HTTP_REFERER', reverse('home'))

    #由于CommentForm没有request,所以要通过实例化表单对象的时候,使用关键字传参把user对象传递给表单
    comment_form = CommentForm(request.POST, user=request.user)

    data = {}
    if comment_form.is_valid():
        comment = Comment()

        #虽然可以像html表单一样对user对验证,但是我们使用form后,应该在表单里做验证,而不是在views里
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']  #从cleaned_data获取
        comment.content_object = comment_form.cleaned_data['content_object']

        #表单字段的数据检查在forms中完成,这里新增判断是否是属于子评论还是主评论,因为保存的数据不一样
        parent = comment_form.cleaned_data['parent']

        #如果parent有数据
        #看下面逻辑前,先解释下parent和root的区别
        #parent就是字面意思评论的直接父节点,没有没有父节点,parent为None,有父节点,那parent就是指向直接父节点
        #root是该评论的根节点,如果是主评论,那root为None,只要是这个根节点下所有评论,这个root都指向这个根节点,如1-2,1-3,1-2-1,1-3-1,1-3-2 的root都是1
        if not parent is None:

            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user

        comment.save()

        # 发送邮件给被评论或者被回复的用户
        # 方式一:使用同步的方式,等邮件发送完后才执行后续的ajax
        if comment.parent is None:
            subject = '有人评论了你的博客'
            email = comment.content_object.get_email()

            # 因为我们要返回给一个链接,点开后是博客详情页,我们可以直接写地址,但是用reverse来反查地址更好
            # 由于blog_detail的url需要传一个参数

            # 第一种做法是传一个args,是一个list
            # text = comment.text + '\n' + reverse('blog_detail', args=[comment.content_object.pk])

            #第二种做法是,关键字传参,是个dict,其中key是url中写的
            # text = comment.text + '\n' + reverse('blog_detail', kwargs={'blog_pk':comment.content_object.pk})

            #第三种做法是,这个链接应该是由content_object来得到,所以要在Blog模型中新增一个get_url的方法,符合封装
            #由于是公共部分,所以都提出去了
            text = comment.text + '\n' + comment.content_object.get_url()

        else:
            subject = '有人回复了你的评论'
            email = comment.reply_to.email

        if email != '':
            text = comment.text + '\n' + comment.content_object.get_url()
            # send_mail(subject, text, settings.EMAIL_HOST_USER, [email], fail_silently=False)

        # # 方式二:使用异步来发送邮件  同样可以放到signals中
        # comment.send_email()

        # # 发送站内消息 (第一种方式) # 第二种方式是用signals
        # if comment.reply_to is None:
        #     # 评论
        #     recipient = comment.content_object.get_user()
        #     if comment.content_type.model == 'blog':
        #         blog = comment.content_object
        #         verb = '{0}评论了你的博客《{1}》'.format(comment.user.get_nickname_or_username(), blog.title)
        #     else:
        #         raise Exception('unkown comment object type')
        # else:
        #     # 回复,其中strip_tags是为了去除html标签
        #     recipient = comment.reply_to
        #     verb = '{0}回复了你的评论“{1}”'.format(comment.user.get_nickname_or_username(), strip_tags(comment.parent.text))
        #
        # # 参数分别表示的意思是:通知者,接收者,接受内容,这个消息是从哪个地方出发的
        # notify.send(comment.user, recipient=recipient, verb=verb, action_object=comment)

        # 未使用ajax提交的代码
        # return redirect(referer)

        # 使用ajax提交的代码
        data['status'] = 'SUCCESS'
        data['username'] = comment.user.get_nickname_or_username()
        # 如果使用下面这个方式,那setting文件中要修改 USE_TZ = False ,然后前端不用拼html时不要调用 时间函数
        data['comment_time'] = comment.comment_time.strftime(
            '%Y-%m-%d %H:%M:%S')
        # data['comment_time'] = comment.comment_time.timestamp()
        data['text'] = comment.text
        data['content_type'] = ContentType.objects.get_for_model(comment).model

        #返回数据也要新增数据
        if not parent is None:
            data['reply_to'] = comment.reply_to.get_nickname_or_username()
        else:
            data['reply_to'] = ''

        data['pk'] = comment.pk
        data['root_pk'] = comment.root.pk if not comment.root is None else ''

    else:
        # 未使用ajax提交的代码
        # return render(request, 'error.html', {'message':comment_form.errors, 'redirect_to':referer}) #返回表单的错误信息errors

        # 使用ajax提交的代码
        data['status'] = 'ERROR'

        # dict.values()是返回字典中所有的值,因为comment_form.errors是个字典,然后我们转为列表,只取第一个错误信息,第二次取[0]是因为还是个数组,再从数组中取出真正的错误信息
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
Exemplo n.º 30
0
def update_comment(request):

    # # 检查数据
    # if not request.user.is_authenticated:
    #     return render(request,'error.html',{'message':'用户未登陆','redirect_to':referer})
    # text = request.POST.get('text', '').strip()
    # if text == '':
    #     return render(request,'error.html',{'message':'评论内容为空','redirect_to':referer})
    # try:
    #
    #     content_type = request.POST.get('content_type','')
    #     object_id = int(request.POST.get('object_id',''))
    #     model_class = ContentType.objects.get(model=content_type).model_class()
    #     model_obj = model_class.objects.get(pk=object_id)
    # except Exception as e:
    #     return render(request,'error.html',{'message':'评论对象不存在','redirect_to':referer})
    # # 检查通过,保存数据
    # comment = Comment()
    # comment.user = request.user
    # comment.text = text
    # comment.content_object = model_obj
    # comment.save()
    #
    # return redirect(referer)
    referer = request.META.get('HTTP_REFERER', reverse('article:index'))
    if not request.user.is_authenticated:
        return render(request, 'error.html', {
            'message': '用户未登陆',
            'redirect_to': referer
        })

    comment_form = CommentForm(request.POST, user=request.user)

    data = {}

    if comment_form.is_valid():

        comment = Comment()

        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']
        parent = comment_form.cleaned_data['parent']
        if not parent is None:
            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user

        comment.save()

        data['status'] = 'SUCCESS'
        data['username'] = comment.user.username
        data['comment_time'] = comment.comment_time.date()
        data['text'] = comment.text
        if not parent is None:
            data['reply_to'] = comment.reply_to.username
        else:
            data['reply_to'] = ''
        data['pk'] = comment.pk
        data['root_pk'] = comment.root.pk if not comment.root is None else ''

    else:
        # return render(request, 'error.html', {'message': comment_form.errors, 'redirect_to': referer})

        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
Exemplo n.º 31
0
def update_comment(request):
    """# 发送此请求的网站
    referer = request.META.get('HTTP_REFERER', reverse('home'))

    # 数据检查
    if not request.user.is_authenticated:
        return render(request, 'error.html', {'message': '用户未登录', 'redirect_to': referer})
    text = request.POST.get('text', '').strip()
    if text == '':
        return render(request, 'error.html', {'message': '评论内容为空', 'redirect_to': referer})

    try:
        content_type = request.POST.get('content_type', '')
        object_id = int(request.POST.get('object_id', ''))
        model_class = ContentType.objects.get(model=content_type).model_class()
        model_obj = model_class.objects.get(pk=object_id)
    except Exception as e:
        return render(request, 'error.html', {'message': '评论对象不存在', 'redirect_to': referer})

    # 检查通过,保存数据
    comment = Comment()
    comment.user = request.user
    comment.text = text
    comment.content_object = model_obj
    comment.save()

    return redirect(referer)"""

    # 发送此请求的网站
    referer = request.META.get('HTTP_REFERER', reverse('home'))
    comment_form = CommentForm(request.POST, user=request.user)
    if comment_form.is_valid():
        # 检查通过,保存数据
        comment = Comment()
        comment.user = comment_form.cleaned_data.get('user')
        comment.text = comment_form.cleaned_data.get('text')
        comment.content_object = comment_form.cleaned_data.get(
            'content_object')

        parent = comment_form.cleaned_data.get('parent')
        if parent is not None:
            comment.parent = parent
            comment.root = parent.root if parent.parent is not None else parent
            comment.reply_to = parent.user
        comment.save()

        # 返回数据
        data = {
            'status':
            'success',
            'username':
            comment.user.get_nickname_or_username(),
            'comment_time':
            comment.comment_time.strftime('%Y-%m-%d %H:%M:%S'),
            'text':
            comment.text,
            'content_type':
            ContentType.objects.get_for_model(comment).model,
            'reply_to':
            comment.reply_to.get_nickname_or_username()
            if parent is not None else '',
            'pk':
            comment.pk,
            'root_pk':
            comment.root.pk if comment.root is not None else ''
        }

        # return redirect(referer)
    else:
        # return render(request, 'error.html', {'message': comment_form.errors, 'redirect_to': referer})
        data = {
            'status': 'error',
            'message': list(comment_form.errors.values())[0][0]
        }
    return JsonResponse(data)
Exemplo n.º 32
0
def update_comment(request):
    '''referer = request.META.get('HTTP_REFERER', reverse('home'))
    user = request.user
    if not user.is_authenticated:
        return render(request, 'error.html', {'message': '用户未登录', 'redirect_to': referer})
    text = request.POST.get('text', '').strip()
    if text == '':
        return render(request, 'error.html', {'message': '评论内容为空', 'redirect_to': referer})

    try:
        content_type = request.POST.get('content_type', '')
        object_id = int(request.POST.get('object_id', ''))
        model_class = ContentType.objects.get(model=content_type).model_class()
        model_obj = model_class.objects.get(pk=object_id)
    except Exception as e:
        return render(request, 'error.html', {'message': '评论对象不存在', 'redirect_to': referer})

    comment = Comment()
    comment.user = user
    comment.text = text
    comment.content_object = model_obj
    comment.save()

    return redirect(referer)'''
    referer = request.META.get('HTTP_REFERER', reverse('home'))
    # if not request.user.is_authenticated:
    #     return render(request, 'error.html', {'message': '用户未登录', 'redirect_to': referer})
    comment_form = CommentForm(request.POST, user=request.user)
    data = {}
    if comment_form.is_valid():
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']

        parent = comment_form.cleaned_data['parent']
        if not parent is None:
            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()

        # 发送邮件通知
        comment.send_email()

        # 返回数据
        data['status'] = 'SUCCESS'
        data['username'] = comment.user.get_nickname_or_username()
        data['comment_time'] = comment.comment_time.strftime(
            '%Y-%m-%d  %H:%M:%S')
        data['text'] = comment.text
        data['content_type'] = ContentType.objects.get_for_model(comment).model
        if not parent is None:
            data['reply_to'] = comment.reply_to.get_nickname_or_username()
        else:
            data['reply_to'] = ''
        data['pk'] = comment.pk
        data['root_pk'] = comment.root.pk if not comment.root is None else ''
    else:
        # return render(request, 'error.html', {'message': comment_form.errors, 'redirect_to': referer})
        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
Exemplo n.º 33
0
def post_comment(request, article_id, parent_comment_id=None):
    article = get_object_or_404(ArticlePost, id=article_id)

    # 处理 POST 请求
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.article = article
            new_comment.user = request.user
            # 二级回复
            if parent_comment_id:
                parent_comment = Comment.objects.get(id=parent_comment_id)
                # 若回复层级超过二级,则转换为二级
                new_comment.parent_id = parent_comment.get_root().id
                # 被回复人
                new_comment.reply_to = parent_comment.user
                new_comment.save()
                # 给其他用户发送通知
                if not parent_comment.user.is_superuser:
                    notify.send(
                        request.user,
                        recipient=parent_comment.user,
                        verb='回复了你',
                        target=article,
                        action_object=new_comment,
                    )
                return JsonResponse({
                    "code": "200 OK",
                    "new_comment_id": new_comment.id
                })
            new_comment.save()

            # 给管理员发送通知
            if not request.user.is_superuser:
                notify.send(
                    request.user,
                    recipient=User.objects.filter(is_superuser=1),
                    verb='回复了你',
                    action_object=new_comment,
                )
            # 添加锚点
            redirect_url = article.get_absolute_url() + '#comment_elem_' + str(
                new_comment.id)
            return redirect(redirect_url)
        else:
            return HttpResponse("表单内容有误,请重新输入")

        return redirect('article:article_detail', id=article_id)

    # 处理 GET 请求
    elif request.method == 'GET':
        comment_form = CommentForm()
        context = {
            'comment_form': comment_form,
            'article_id': article_id,
            'parent_comment_id': parent_comment_id
        }
        return render(request, 'comment/reply.html', context)
    # 处理错误请求
    else:
        return HttpResponse("发表评论仅接受POST请求")