示例#1
0
 def test_form_validation_for_empty_textarea(self):
     form = CommentForm(data={'text': ''})
     self.assertFalse(form.is_valid())
     self.assertEqual(
         form.errors['text'],
         [TEXT_EMPTY_ERROR]
     )
示例#2
0
def comment_create(request, pk):
    if request.method == 'POST':
        post = get_object_or_404(Post, pk=pk)
        # content = request.get('content')
        #
        # if not content:
        #     return HttpResponse('댓글내용을 입력하세요.', status=400)
        #
        # Comment.objects.create(
        #     author=request.user,
        #     post=post,
        #     content=content,
        # )
        # return redirect()

        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()

            messages.success(request, '댓글이 등록되었습니다')
        else:
            error_msg = '댓글 등록에 실패했습니다\n{}'.format(
                '\n'.join(
                    [f'- {error}'
                     for key, value in comment_form.errors.items()
                     for error in value]))
            messages.error(request, error_msg)

        return redirect('post:post-detail', pk=pk)
示例#3
0
文件: views.py 项目: vladymir/myblog
def view_post(request, slug=None):
	try:
		post = Post.objects.get(slug=slug)
	except ObjectDoesNotExist:
		raise Http404
	if request.method == 'POST':
		comment = Comment(post=post)
		comment_form = CommentForm(request.POST, instance=comment)
		if comment_form.is_valid():
			comment_form.save()
			comment_form1 = CommentForm()
			comments = post.comment_set.filter(status__exact='A')
			context = RequestContext(request, { 'post' : post, 
				'comment_form' : comment_form1, 
				'comments' : comments,
				'len_comments' : len(comments)})
			return render_to_response('post.html', context)
		else:
			return HttpResponseRedirect(post.get_absolute_url())
	else:
		comments = post.comment_set.filter(status__exact='A')
		comment = CommentForm()
		context = RequestContext(request, { 'post' : post, 
			'comment_form': comment, 
			'comments':comments,
			'len_comments' : len(comments)})
		return render_to_response('post.html', context)
	return HttpResponse('/')
示例#4
0
文件: helpers.py 项目: mrfishball/O2
def post_preprocessor(data, **kwargs):
    form = CommentForm(data=data)
    if form.validate():
        return form.data
    else:
        raise ProcessingException(description='Invalid form submission.',
                                  code=400)
def add_comment(request, username, post_id):
    post = get_object_or_404(Post, id=post_id, author__username=username)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        form.instance.author = request.user
        form.instance.post = post
        form.save()
    return redirect('post', username=username, post_id=post_id)
    def post(self, request, pk, *args, **kwargs):
        user = request.user
        profile = Profile.objects.get(user=user)
        group = Group.objects.get(pk=pk)

        # Custom profanity words
        custom_badwords = CustomProfanity.objects.values_list('bad_word',
                                                              flat=True)
        profanity.load_censor_words(custom_badwords)

        if 'submit_post_form' in request.POST:
            post_form = PostForm(request.POST, request.FILES)
            comment_form = None
            valid = post_form.is_valid()

            if profanity.contains_profanity(
                    post_form.cleaned_data.get('content')):
                custom_profanity_error = 'Please remove any profanity/swear words. (Added by an admin. Contact an admin if you believe this is wrong.)'
                valid = False
                post_form.errors['content'] = custom_profanity_error

            if valid:
                post_instance = post_form.save(commit=False)
                post_instance.author = profile
                post_instance.group = group
                post_instance.save()
                return redirect('groups:view-group', pk=pk)

        elif 'submit_comment_form' in request.POST:
            comment_form = CommentForm(request.POST)
            post_form = None
            valid = comment_form.is_valid()

            if profanity.contains_profanity(
                    comment_form.cleaned_data.get('body')):
                custom_profanity_error = 'Please remove any profanity/swear words. (Added by an admin. Contact an admin if you believe this is wrong.)'
                valid = False
                comment_form.errors['body'] = custom_profanity_error

            if valid:
                post_id = request.POST.get("post_id")
                comment_instance = comment_form.save(commit=False)
                comment_instance.user = profile
                comment_instance.post = Post.objects.get(id=post_id)
                comment_instance.save()
                return redirect(request.headers.get('Referer'))

        group_posts = Post.objects.filter(group=group)

        context = {
            'profile': profile,
            'group': group,
            'posts': group_posts,
            'post_form': post_form,
            'comment_form': comment_form
        }

        return render(request, 'groups/view.html', context)
示例#7
0
def add_comment(request, username, post_id):
    post = get_object_or_404(Post, author__username=username, id=post_id)
    comment_form = CommentForm(request.POST or None)
    if comment_form.is_valid:
        instance_comment = comment_form.save(commit=False)
        instance_comment.post = post
        instance_comment.author = request.user
        instance_comment.save()
    return redirect("post", username=username, post_id=post_id)
def CommentView(request, id):
    post = get_object_or_404(Post, pk=id)
    form = CommentForm(request.POST)

    if form.is_valid():
        my_new_todo = Post(commentext=request.POST['text'])
        my_new_todo.save()

    return redirect('post_detail', pk=post.pk)
示例#9
0
 def post(self, request, titleslug, comment_id):
     # This method posts the subcomment
     post = Post.objects.get(titleslug=titleslug)
     comment = Comment.objects.get(id=comment_id)
     form = CommentForm(request.POST)
     if form.is_valid():
         form.save()
         return redirect("/posts/{}/{}".format(titleslug, comment_id))
     else:
         return render(request, "posts/commentpage.html", {"form": form})
示例#10
0
def add_comment(request, username, post_id):
    post = get_object_or_404(Post, author__username=username, id=post_id)
    form = CommentForm(request.POST or None)
    if request.method != "POST" or not form.is_valid():
        return redirect('posts:post', post.author, post.id)
    comment = form.save(commit=False)
    comment.post = post
    comment.author = request.user
    comment.save()
    return redirect(reverse("posts:post", args=[post.author, post.id]))
示例#11
0
 def comment(self, request, pk):
     post = get_object_or_404(Post, pk=pk)
     form = CommentForm(request.POST)
     if request.method == "POST":
         if form.is_valid():
             comment = form.save(commit=False)
             comment.post = post
             comment.save()
             return HttpResponseRedirect(
                 reverse('posts-details-page', args=[pk]))
     return render(request, 'post.html', {'form': form})
示例#12
0
 def post(self, request, titleslug):
     # This method posts the entered comment if valid and returns the user to
     # the post page
     post = Post.objects.get(titleslug=titleslug)
     user = User.objects.get(username=request.user)
     form = CommentForm(request.POST)
     if form.is_valid():
         form.save()
         return redirect("/posts/{}".format(titleslug))
     else:
         return render(request, "posts/postpage.html", {"form": form})
示例#13
0
def comment(request, pk):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            p = Post.objects.get(pk=pk)
            c = Comment.objects.create(body=request.POST['body'],
                                       user_id=request.user, post_id=p)
            return JsonResponse({'message': c.body})
        else:
            return JsonResponse({'message': 'error'})
    return redirect('post', pk)
示例#14
0
def profile(request, username, profile=None, user_profile=None):
    if profile is None:
        profile = Profile.objects.get(user=User.objects.get(username=username))

    posts = profile.posts.order_by('-post_date').all()
    paginador = Paginator(posts, 10)
    page = request.GET.get('page')
    posts = paginador.get_page(page)

    if request.user.is_authenticated:
        if request.user.username == username:
            return render(
                request, 'profile.html', {
                    'profile': profile,
                    'comment_form': CommentForm(),
                    'share_form': SharePostForm(),
                    'user_profile': Profile.objects.get(user=request.user),
                    'posts': posts
                })

        friendship = 0
        invitation = None
        try:
            invitation = Invitation.objects.get(
                Q(sender__user__username=request.user.username,
                  receiver__user__username=username)
                | Q(sender__user__username=username,
                    receiver__user__username=request.user.username))
        except Invitation.DoesNotExist:
            pass

        if invitation is not None:
            if invitation.sender.user == request.user:
                friendship = 1
            if invitation.sender.user == profile.user:
                friendship = 2
        elif profile.contacts.filter(user=request.user).exists():
            friendship = 3

        return render(
            request, 'profile.html', {
                'user_profile': Profile.objects.get(user=request.user),
                'comment_form': CommentForm(),
                'share_form': SharePostForm(),
                'profile': profile,
                'friendship': friendship,
                'invitation': invitation,
                'posts': posts
            })

    return render(request, 'profile.html', {
        'profile': profile,
        'posts': posts
    })
示例#15
0
def add_comment(request, username, post_id):
    """Добавление комментария."""
    author = get_object_or_404(User, username=username)
    post = get_object_or_404(author.author_posts, id=post_id)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.author = request.user
        comment.post_id = post_id
        comment.save()
        return redirect('post_view', username=username, post_id=post_id)
    return render(request, 'comments.html', {'form': form, 'post': post})
示例#16
0
def add_comment(request, username, post_id):
    author = get_object_or_404(User, username=username)
    post = get_object_or_404(author.posts, pk=post_id)

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

    return redirect('post_view', username, post.id)
示例#17
0
def add_comment(request, username, post_id):
    form = CommentForm(request.POST or None)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.post = get_object_or_404(Post,
                                         author__username=username,
                                         id=post_id)
        comment.author = request.user
        comment.save()
        return redirect('post_view', username, post_id)
    return render(request, 'new_comment.html', {
        'form': form,
    })
def add_reply_on_comment(request, username, post_id, comment_id):
    post = get_object_or_404(Post, id=post_id, author__username=username)
    comment = get_object_or_404(Comment, id=comment_id)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        form.instance.post = post
        form.instance.author = request.user
        form.instance.reply = comment
        form.save()
    return render(request, 'posts/comments.html', {
        'post': post,
        'form': CommentForm
    })
示例#19
0
def comment_create(request, id):
    post = get_object_or_404(Post, pk=id)

    form = CommentForm(request.POST)
    form.instance.post = post
    form.instance.content = request.POST.get('content')
    if form.is_valid():
        form.save()
        messages.success(request, 'Thanks for your comment!!.')
        return redirect(reverse('post_details', kwargs={'id': post.id}))
    else:
        messages.warning(request, 'Sorry, something went wrong!!.')
        return redirect(post_list)
示例#20
0
def detail(request, pk):
    post = Posts.objects.get(id=pk)
    comments = post.comments.all()

    form = CommentForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.post = post
        instance.save()
        return HttpResponseRedirect(post.get_absolute_url())

    context = {"post": post, "comments": comments, "form": form}
    return render(request, "detail.html", context)
示例#21
0
def add_comment_to_post(request,pk):
    if request.method =="POST":
        post=get_object_or_404(models.Post,pk=pk)
        form=CommentForm(request.POST)
        if form.is_valid():
            post_comment=form.save(commit=False)

            post_comment.author = request.user
            post_comment.text = request.POST["comment"]
            post_comment.post  = post
            post_comment.save()

            return redirect("posts:post_detail",pk=post.pk)
    else:
        return redirect("posts:post_detail",pk=post.pk)
示例#22
0
    def setUpClass(cls):
        super().setUpClass()
        cls.form = PostForm()
        cls.form_comment = CommentForm()

        User = get_user_model()
        cls.user2 = User.objects.create(username="******")
        cls.user = User.objects.create(username="******")

        cls.authorized_client = Client()
        cls.authorized_client.force_login(cls.user)

        cls.group = Group.objects.create(
            title="Заголовок",
            description="Описание",
            slug="Slug_test",
        )

        cls.post = Post.objects.create(author=PostFormTests.user,
                                       text="Какой-нибудь текст",
                                       group=cls.group)

        cls.comment = Comment.objects.create(
            post=cls.post,
            author=PostFormTests.user,
            text="Текст тестового комментария",
        )
示例#23
0
文件: views.py 项目: gh720/blog_test
 def get_context_data(self, *, object_list=None, **kwargs):
     ctx = super().get_context_data(**kwargs)
     ctx['comment_form'] = ctx.get('comment_form', CommentForm())
     # obj = super().get_object()
     self.object.set_can_edit(self.request)
     # ctx['can_edit'] = self.object.can_edit(self.object)
     return ctx
示例#24
0
def search(request):
    q1 = request.GET.get('question')
    Q = q1.split(' ')
    if Q == ['']:
        return redirect('mywall')
    i = 0
    results = Post.objects.none()
    while i < len(Q):
        results = results | Post.objects.filter(text__icontains=Q[i])[:10]
        i += 1
    profile = Profile.objects.get(user=request.user)
    if profile.has_unread_notif():
        notif = True
    else:
        notif = False
    subscrib_onme = Subscrib.objects.filter(to=request.user)
    my_subscribs = Subscrib.objects.filter(who=request.user)
    form_com = CommentForm(prefix='comment')
    context = {
        'results': results,
        'profile': profile,
        'notif': notif,
        'subscrib_onme': subscrib_onme,
        'my_subscribs': my_subscribs,
        'form_com': form_com
    }
    return render(request, 'root/search_results.html', context)
示例#25
0
def view_account(request, slug):
    profile = get_object_or_404(Profile, slug=slug)
    user = profile.user
    current_user = request.user

    # Used when loading the view without any button clicks
    # (to determine the color and text of the following button).
    is_following = current_user.profile.following.\
        filter(pk=profile.id).exists()
    is_followed = current_user.profile.followers.\
        filter(pk=profile.id).exists()

    posts_list = user.posts.all()
    posts = get_paginated_posts(request, posts_list)
    args = {
        'user': user,
        'profile': profile,
        'current_user': current_user,
        'posts': posts,
        'is_following': is_following,
        'is_followed': is_followed,
        'comment_form': CommentForm()
    }

    if user == current_user and request.method == 'GET':
        post_form = PostForm()
        args.update({'post_form': PostForm()})

    return render(request, 'accounts/view_account.html', args)
示例#26
0
def view_post(request, url):	
	post = get_object_or_404(Post, url=url)     	
	form = CommentForm(request.POST or None)
	if form.is_valid():
		comment = form.save(commit=False)
		comment.post = post
		comment.name=request.user.username
		comment.profile=request.user.profile
		comment.save()
		request.session["name"] = comment.name

		return redirect(request.path)

	form.initial['name'] = request.session.get('name')

	return render(request, 'posts/detail.html',{'post': post, 'form':form, })
示例#27
0
def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    comment_form = CommentForm()
    context = {
        'post': post,
        'comment_form': comment_form,
    }
    return render(request, 'posts/post_detail.html', context)
示例#28
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        comments = Comment.objects.filter(
            post=self.get_object()).order_by('-created')
        context['comments'] = comments
        context['CommentForm'] = CommentForm(instance=self.request.user)
        return context
示例#29
0
 def get_context_data(self, **kwargs):
     context = super(PostView, self).get_context_data(**kwargs)
     context['form'] = CommentForm()
     post = Post.objects.get(slug=self.kwargs.get('slug'))
     context['comments'] = Comment.objects.filter(
         post=post).order_by('-created_at')
     context['title'] = post.title
     return context
示例#30
0
def post_detail(request, post_pk):
    post = Post.objects.get(pk=post_pk)

    context = {
        'post': post,
        'comment_form': CommentForm(),
    }
    return render(request, 'posts/post_detail.html', context)
示例#31
0
def post_list(request):
    posts = Post.objects.all()
    comment_form = CommentForm()
    context = {
        'posts': posts,
        'comment_form': comment_form,
    }
    return render(request, 'posts/post_list.html', context)
示例#32
0
def p_read(request, post_id):

    post = get_object_or_404(Post, pk=post_id)
    session = request.session['user']
    if request.method == 'POST':
        # POST 방식으로 호출 될 때
        user_id = request.session.get('user')
        user = User.objects.get(username=user_id)
        comment = Comment(post=post, author=user_id)
        comment_form = CommentForm(request.POST, instance=comment)

        if comment_form.is_valid():

            comment_form.save()
            return redirect(f'/posts/{post_id}/read')

    else:
        # GET 방식으로 호출 될 때
        comment_form = CommentForm()

        context = {
            'post': post,
            'comment_form': comment_form,
            'session': session
        }
    return render(request, 'read.html', context)
示例#33
0
def post(request, id):
    post = get_object_or_404(Post, id=id)

    if request.user.is_authenticated:
        PostView.objects.get_or_create(user=request.user, post=post)

    form = CommentForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = post
            form.save()
            return redirect(reverse("post_detail", kwargs={'id': post.pk}))
    context = {
        'form': form,
        'post': post,
    }
    return render(request, 'post.html', context)
示例#34
0
def comment_create(request, post_pk):
    # 1. post_pk 해당하는 Post 객체를 가져와  post 변수에 할당
    # 2. request.POST 에 전달 된 'content'키의 값을 content 변수에 할당
    # 3. Comment생성
    #   author : 현재 요청의 유저
    #   post : post_pk에 해당하는 Post객체
    #   content : request.POST로 전달 된 'content'키의 값
    # 4. posts:post-list로 redirect
    if request.method == 'POST':
        post = Post.objects.get(pk=post_pk)
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.post = post
            comment.save()

            return redirect('posts:post-detail', post_pk)
示例#35
0
def detail(request, post_id):
    try:
        post = Post.objects.get(pk=post_id)
    except Post.DoesNotExist:
        raise Http404
    #return render(request, 'posts/detail.html', {'post': post})

    if request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']

            c = Comment(content=content, post_id=post_id, user_id=request.user.id)
            c.save()

            return HttpResponseRedirect(reverse('posts:detail', args=[post_id]))
        else:
            render(request, 'posts/detail.html', {'post': post, 'form': form})
    else:
        form = CommentForm()
    form = CommentForm()
    return render(request, 'posts/detail.html', {'post': post, 'form': form})
示例#36
0
def create_comments(request, **kwargs):
    # ipdb.set_trace()
    post = get_object_or_404(Post, slug=kwargs["slug"])
    node_set = post.comment_set.all()

    if request.method == "POST":
        form = CommentForm(request.POST)

        if form.is_valid():
            user_obj = request.user
            form.instance.fk_user = user_obj
            try:
                post_obj = Post.objects.get(slug=kwargs["slug"])
                form.instance.fk_post = post_obj

                # if reply
                if kwargs.has_key("p_id"):
                    form.instance.parent_cmt = Comment.objects.get(id=kwargs["p_id"])

                form.save()
                form.save()
                node_set = post_obj.comment_set.all()
            except ObjectDoesNotExist:
                raise Http404

            return render(request, "posts/post_detail.html", {"post": post_obj, "node_set": node_set})

        else:
            form = CommentForm()
            if kwargs.has_key("p_id"):
                form.instance.parent_cmt = Comment.objects.get(id=kwargs["p_id"])
                form_type = "reply_"
            else:
                form_type = "comment_"

    else:
        form = CommentForm()
        if kwargs.has_key("p_id"):
            form.instance.parent_cmt = Comment.objects.get(id=kwargs["p_id"])
            form_type = "reply_"
        else:
            form_type = "comment_"

    return render(
        request, "posts/comment_form.html", {"form": form, "post": post, "node_set": node_set, "form_type": form_type}
    )
示例#37
0
def expand_post(request,post_id):
    if request.user.is_authenticated():
        my_profile = Profile.objects.get(user=request.user)
    try:
        post = Post.objects.get(uuid=post_id)
    except:
        hosts = Host.objects.all()
        for host in hosts:
            if host.name == "Group3":
                try:
                    post_json = host.get_postid(post_id)['posts'][0]
                    visibility = post_json['visibility']
                    description = post_json['description']
                    date = timezone.make_aware(datetime.datetime.strptime(post_json['pubdate'], '%Y-%m-%d'), timezone.get_default_timezone())
                    title = post_json['title']
                    content = post_json['content']
                    content_type = post_json['content-type']

                    author_id = post_json['author']['id']
                    author_host = post_json['author']['host']
                    author_displayname = post_json['author']['displayname']
                    try:
                        author_user = User(username=author_displayname+'@Group3',
                                            password="")
                        author_user.save()
                        author_profile = Profile(user=author_user,uuid=author_id,
                        displayname=author_displayname,host=author_host)
                        author_profile.save()
                    except:
                        author_profile = Profile.objects.get(uuid=author_id)

                    post = Post(title=title,post_text=content,author=author_profile,date=date,privacy='1')
                    comments = []
                    comment_form = []
                    return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile})
                except:
                    pass
            elif host.name == "Group7":
                try:
                    post_json = host.get_postid(post_id)['posts'][0]
                    print(post_json)
                    #visibility = post_json['visibility']
                    description = post_json['description']
                    date = date = timezone.make_aware(datetime.datetime.strptime('2015-04-01', '%Y-%m-%d'), timezone.get_default_timezone())
                    title = post_json['title']
                    content = post_json['content']
                    content_type = post_json['content-type']

                    author_id = post_json['author']['id']
                    author_host = post_json['author']['host']
                    author_displayname = post_json['author']['displayname']
                    try:
                        author_user = User(username=author_displayname+'@Group3',
                                            password="")
                        author_user.save()
                        author_profile = Profile(user=author_user,uuid=author_id,
                        displayname=author_displayname,host=author_host)
                        author_profile.save()
                    except:
                        author_profile = Profile.objects.get(uuid=author_id)

                    post = Post(title=title,post_text=content,author=author_profile,date=date,privacy='1')
                    comments = []
                    comment_form = []
                    return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile})
                except:
                    pass

    try:
        if post.content_type == 'text/x-markdown':
            post.post_text = markdown2.markdown(post.post_text)
        current_profile = Profile.objects.get(user_id=request.user.id)
        comments = None
        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)

            if comment_form.is_valid():
                body = comment_form.cleaned_data['body']
                newComment = Comment(body=body, date=timezone.now(), author=current_profile, post_id=post)
                newComment.save()
            else:
                print comment_form.errors
            return redirect('/posts/'+post_id)
        else:
            comments = Comment.objects.filter(post_id=post).order_by('date')
            comment_form = CommentForm()
        return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile})
    except:
        return HttpResponse("Post not found", status=404)