コード例 #1
0
ファイル: views.py プロジェクト: iskeltan/blox
def add_comment(request, post_id, obj_name, obj_id):
    if request.method == "POST":
        post = get_object_or_404(Post, pk=post_id)
        if obj_name == "post":
            parent_object = post
        elif obj_name == "comment":
            parent_object = get_object_or_404(Comment, pk=obj_id)
        else:
            return HttpResponseRedirect("/?err=postmucommentmiparentin")
        
        initial_data = {"post": post, "parent_object": parent_object, "user": request.user }

        if request.user.is_authenticated():
            comment_form = CommentForm(request.POST, initial=initial_data)
            messages.info(request, _("your comment has been added"))
        else:
            comment_form = CommentForm_no_auth(request.POST, initial=initial_data)
            messages.info(request, _("your comment has been added but must confirm with email required "))

        if comment_form.is_valid():
            comment_form.save()
            return HttpResponseRedirect(reverse("detail", args=[post_id]))
        else:
            messages.warning(request, _("this comment is not valid "))
            return HttpResponseRedirect(reverse("detail", args=[post_id]))
    else:
        return HttpResponseRedirect("/")
コード例 #2
0
ファイル: views.py プロジェクト: MrYurchik/MainHW
def new_single(request, pk):
    #ВИВІД ВСІЄЇ СТАТІ
    new = get_object_or_404(News, id=pk)
    comment = Com.objects.filter(
        new=pk
    )  #берем комент з бази + moderation=True якшо потрібно проходити провірку можератором

    if request.method == "POST":
        form = CommentForm(request.POST)
        #присвоюэм коменту користувача
        if form.is_valid():  #якшо пост то обробляэм і выдправляэм
            form = form.save(commit=False)
            form.user = request.user
            form.new = new
            form.save()
            return redirect(new_single, pk)
        #Якшо GET то відправляєм форму
    else:
        form = CommentForm()

    return render(request, 'post/new_single.html', {
        'new': new,
        "comments": comment,
        "form": form
    })
コード例 #3
0
ファイル: comment.py プロジェクト: Gyong1211/Instagram
def comment_create(request, post_pk):
    # post = Post.objects.get(pk=post_pk)
    # form = CommentForm(data=request.POST)
    # user = request.user
    # if form.is_valid():
    #     Comment.objects.create(post=post, author=user, content=form.cleaned_data['content'])
    # return redirect('post:post_detail', post_pk)
    post = get_object_or_404(Post, pk=post_pk)
    form = CommentForm(data=request.POST)
    next = request.GET.get('next')
    if form.is_valid():
        comment = form.save(commit=False)
        comment.author = request.user
        comment.post = post
        form.save()
        email = EmailMessage('댓글 알림',
                             '당신의 포스트에 {}님의 댓글이 달렸습니다.'.format(request.user),
                             to=[post.author.email])
        email.send()
    else:
        e = '<br>'.join(['<br>'.join(v) for v in form.errors.values()])
        messages.error(request, e)

    if next:
        return redirect(next)
    return redirect('post:post_detail', post_pk)
コード例 #4
0
ファイル: views.py プロジェクト: petrosernivka/book
def addcomment(request, post_id):
    if request.POST and ('pause' not in request.session):
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comments_post = Post.objects.get(id=post_id)
            comment.comments_date = datetime.now()
            comment.comments_author = User.objects.get(id=request.user.id)
            form.save()
            request.session.set_expiry(10)
            request.session['pause'] = True
    return redirect('/posts/get/{}/'.format(post_id))
コード例 #5
0
def post(request, post_id):
    post = Post.objects.get(id=post_id)

    # Instantiate the CommentForm class here. At this
    # point in our workflow, the user has already made
    # a request to view, so we know what the post_id
    # is that they are viewing. Since our Comment Model
    # (and likewise, the Comment ModelForm) are tied to 
    # a specific Post pk, we can just pass in that pk
    # to our form (this means the user won't have to
    # select the post they want to comment on from
    # a dropdown.)
    form = CommentForm(initial={'post': post.pk})
    
    # Remember how I said we have access to everything
    # about the request in the view? Well this comes in
    # handy when dealing with forms! When you make a GET
    # request to a post URL, we load the form. If you submit
    # the form via a POST, we can use this if condition to
    # reinitialize our CommentForm with the data from the POST
    # (IE, the comment text).
    if request.method == "POST":
        # At this point in the workflow,
        # we are dealing with a bound form. A bound form has
        # data associated with it. 
        form = CommentForm(request.POST)
        # Next, Django makes it REALLY easy to check if our form is
        # valid. By calling form.is_valid(), we know if the form was
        # submitted correctly, or if it should be rerendered with
        # the appropriate errors (for example, if you didn't
        # submit the form with all of the required fields filled in) 
        if form.is_valid():
            # remember, a bound, valid ModelForm is just a model instance
            # ready to be saved to the database! Rememeber when we called
            # post.save() in the shell and the post was committed to the
            # database? That's exactly what we're doing here.
            form.save()
            # Finally, let's redirect the user back to the post they were just on.
            return redirect('/post/{}/'.format(post_id))

    # Woa, what's this "comment_set" nonsense? It's a helper method Django gives
    # us that allows us to grab the _set_ of _comments_ associated to a post!
    # It's the same as using "Comment.objects.filter(post=post)"
    # 
    # https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
    comments = post.comment_set.all() 

    # Finally, here is our updated context! 
    # Along with post, we're passing in `form` and `comments`
    context = {'post': post, 'form': form, 'comments': comments}
    return render(request, 'post.html', context)
コード例 #6
0
def comment_modify(request, comment_pk):
    comment = get_object_or_404(Comment, pk=comment_pk)
    next = request.GET.get('next')
    if request.method == 'POST':
        form = CommentForm(request.POST, instance=comment)
        form.save()
        if next:
            return redirect(next)
        return redirect('post:post_detail', post_pk=comment.post.pk)
    else:
        form = CommentForm(instance=comment)
    context = {
        'form': form,
    }
    return render(request, 'post/comment_modify.html', context)
コード例 #7
0
def comment_create(request, post_pk):
    # POST 요청을 받아 Comment객체를 생성 후 post_detail페이지로 redirect
    # CommentForm을 만들어서 해당 ModelForm안에서 생성/수정가능하도록 사용
    # URL에 전달된 post_pk로 특정 Post 객체 가져옴
    post = get_object_or_404(Post, pk=post_pk)
    # GET요청시 parameter중 'next'의 value값을 next_에 할당
    next_ = request.GET.get('next')
    # CommentForm data binding
    form = CommentForm(data=request.POST)
    if form.is_valid():
        # comment변수에 commit=False의 결과인 인스턴스를 할당
        comment = form.save(commit=False)
        # comment의 author와 post를 각각 지정해준다.
        comment.author = request.user
        comment.post = post
        # save() 메서드 실행
        comment.save()
        # next로 이동할 url이 있다면 그쪽으로 이동시킴
    else:
        result = '<br>'.join(['<br>'.join(v) for v in form.errors.values()])
        messages.error(request, result)
    if next_:
        return redirect(next_)
    # next_값이 없다면 post_detail로 이동
    return redirect('post:post_detail', post_pk=post.pk)
コード例 #8
0
ファイル: views.py プロジェクト: palladine/testsite
def postbyid(request, post_id):
    fieldstopost = Post.objects.get(id=post_id)
    commentsofpost = Comment.objects.filter(comment_post_id=post_id)
    form = CommentForm()
    if request.POST:
      form = CommentForm(request.POST)
      if form.is_valid():
          onecom = form.save(commit=False)
          onecom.comment_post = Post.objects.get(id=post_id)
          form.save()
          return redirect('/post/%s/' % post_id)
    return render_to_response('paper/post.html', 
            {'postfull': fieldstopost, 
             'commentsofpost': commentsofpost,
             'commentform': form},
             context_instance=RequestContext(request, processors=[]))
コード例 #9
0
def postdetail(request, slug):
    post = get_object_or_404(Post, slug=slug)
    comments = post.comments.all()
    new_comment = None

    if request.method == "POST":
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():

            # Create Comment object but don't 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(f"/{slug}")
    else:
        comment_form = CommentForm()

    return render(
        request, 'postdetail.html', {
            "post": post,
            "comments": comments,
            "new_comment": new_comment,
            "comment_form": comment_form,
        })
コード例 #10
0
def detail_post_view(request, slug):
	context = {}

	user = request.user

	if not user.is_authenticated:
		return redirect("login")

	try:
		post = Post.objects.get(slug=slug)
	except Post.DoesNotExist:
		return redirect("home")

	context['current_post'] = post

	if Like.objects.filter(liker=user, post=post).exists():
		context['liked'] = 'liked'

	comment = Comment.objects.filter(post=post)
	context['comments'] = comment

	like_count = Like.objects.filter(post=post).count()
	context['like_count'] = like_count

	form = CommentForm(request.POST)
	if form.is_valid():
		obj = form.save(commit=False)
		obj.commenter = user
		obj.post = post
		obj.save()
		return redirect('post:detail_post' , post.slug)

	return render(request, 'post/detail_post.html', context)
コード例 #11
0
def comment_modify(request, comment_pk):
    # 코멘트 수정창을 만들어 기존의 내용을 채워넣을 수 있게 해야한다.
    comment = get_object_or_404(Comment, pk=comment_pk)
    if request.method == "POST":
        form = CommentForm(data=request.POST, instance=comment)
        if form.is_valid():
            form.save()
            # Form을 이용해 객체를 update시킴 (data에 포함된 부분만 update됨)
            # next_ = request.GET[]
            return redirect('post:post_list')
    else:
        form = CommentForm(instance=comment)
    context = {
        'form': form,
    }
    return render(request, 'post/comment_modify.html', context)
コード例 #12
0
def comment_create(request, post_pk):
    # POST요청을 받아 Comment객체를 생성 후 post_detail페이지로 redirect
    post = get_object_or_404(Post, pk=post_pk)
    next = request.GET.get('next')
    form = CommentForm(request.POST)

    # form 이 유효할 경우, Comment생성
    if form.is_valid():
        comment = form.save(commit=False)
        comment.author = request.user
        comment.post = post
        comment.save()

        mail_subject = '{}에 작성한 글에 {}님이 댓글을 작성했습니다'.format(
            post.created_date.strftime('%Y.%m.%d %H:%M'), request.user)
        mail_content = '{}님의 댓글\n{}'.format(request.user, comment.content)
        send_mail(
            mail_subject,
            mail_content,
            '*****@*****.**',
            [post.author.email],
        )

        # message = EmailMessage(mail_subject, mail_content, to=[post.author.email])
        # message.send()

    else:
        result = '<br>'.join(['<br>'.join(v) for v in form.errors.values()])
        messages.error(request, result)
    if next:
        return redirect(next)
    return redirect('post:post_detail', post_pk=post.pk)
コード例 #13
0
ファイル: views.py プロジェクト: jayveerkher/Django-Projects
def post_detail_view(request, year, month, day, slug):
    post = get_object_or_404(Post,
                             slug=slug,
                             status='published',
                             publish__year=year,
                             publish__month=month,
                             publish__day=day)
    #for comment purpose
    comments = post.comments.filter(active=True)
    csubmit = False
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            new_comment = form.save(
                commit=False
            )  #User only take data like name,email,comment but we require more data related to post
            new_comment.post = post  # post object is already there
            new_comment.save()
            csubmit = True
    else:
        form = CommentForm()
    return render(request, 'post/post_detail.html', {
        'post': post,
        'form': form,
        'csubmit': csubmit,
        'comments': comments
    })
コード例 #14
0
ファイル: views.py プロジェクト: Ogeneral/website
def add_comment(request, post_id):
    form = CommentForm(request.POST or None)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.save()
        return redirect('http://localhost:8000/posts/')
    return render(template_name='detail3.html',
                  context={"form": form},
                  request=request)
コード例 #15
0
def single_info(request, pk):
    info = get_object_or_404(Info, id=pk)
    comments = Comment.objects.filter(info=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            form.client = request.user
            form.info = info
            form.save()
            return redirect(single_info, pk)
    else:
        form = CommentForm()
    return render(request, "info/info_single.html", {
        "info": info,
        "comments": comments,
        "form": form
    })
コード例 #16
0
def comment_modify(request, comment_pk):
    # CommentForm을 만들어서 해당 ModelForm안에서 생성/수정 가능하도록
    comment = get_object_or_404(Comment, pk=comment_pk)
    next = request.GET.get('next')
    if request.method == 'POST':
        # Form을 이용해 객체를 update시킴 (data에 포함된 부분만 update됨)
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            form.save()
            if next:
                return redirect(next)
            return redirect('post:post_detail', post_pk=comment.post.pk)
    else:
        # CommentForm에 기존 comment인스턴스의 내용을 채운 bound form
        form = CommentForm(instance=comment)
    context = {
        'form': form,
    }
    return render(request, 'post/comment_modify.html', context)
コード例 #17
0
ファイル: comment.py プロジェクト: jcasmer/blog
    def post(self, request, *args, **kwargs):
        """
        Muestra el formulario 
        """
        form = CommentForm(request.POST)
        if not form.is_valid():
            post = self.get_post(kwargs['id'])
            comments = self.get_commentary(kwargs['id'])
            messages.error(request, 'Valide los errores')
            output = {
                'post': post,
                'form': form,
                'comments': comments,
            }
            return render(request, self.template_name, output)

        form.save()
        messages.success(request, 'Comentario registrado exitosamente')
        return HttpResponseRedirect(
            reverse('post:list', kwargs={'id': kwargs['id']}))
コード例 #18
0
def comment_create(request, post_pk):
    if request.method == 'POST':
        post = get_object_or_404(Post, pk=post_pk)
        next = request.GET.get('next')
        print('next: {}========='.format(next))
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.post = post
            form.save()
        else:

            result = '<br>'.join(
                ['<br>'.join(v) for v in form.errors.values()])
            messages.error(request, result)

        if next:
            return redirect(next)
        return redirect('post:post_detail', post_pk=post.pk)
コード例 #19
0
def post_card(request, pk):
    post = get_object_or_404(Post, id=pk)
    comment = Comments.objects.filter(post=pk, moderation=True)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            form.user = request.user
            form.post = post
            form.save()
            return redirect(post_card, pk)
    else:
        form = CommentForm()
    return render(
        request,
        'post/post_card.html',
        {
            'post': post,
            # 'comments': comment,
            'form': form
        })
コード例 #20
0
def add_comment(request, post_id):
    post = get_object_or_404(Post, id=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('post:detail', id=post.id)
    else:
        form = CommentForm
        context = {"form": form}
コード例 #21
0
ファイル: views.py プロジェクト: Ogeneral/website
def detail(request, post_id):
    p = Post.objects.get(pk=post_id)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.save()
        return redirect('http://localhost:8000/posts/')
    p = Post.objects.get(pk=post_id)
    return render_to_response('detail3.html',
                              context={
                                  'post': p,
                                  'form': form
                              })
コード例 #22
0
ファイル: views.py プロジェクト: OfficialRuby/dj-blog
def post(request, myid):
    post = get_object_or_404(Post, id=myid)
    form = CommentForm(request.POST or None)
    if request.user.is_authenticated:
        Post_View.objects.get_or_create(user=request.user, post=post)

    if request.method == "POST":
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = post  # From post = get_object_or_404(Post, id=myid)
            form.save()
            return redirect(reverse("post-detail", kwargs={"myid": post.id}))

    category_count = get_category_count()
    most_recent = Post.objects.order_by("-timestamp")[:3]

    context = {
        "form": form,
        "post": post,
        "most_recent": most_recent,
        "category_count": category_count
    }
    return render(request, "post.html", context)
コード例 #23
0
def add_comment(request, post_id):
    post = get_object_or_404(Post, id=post_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('http://127.0.0.1:8000/posts/', id=post.id)
    else:
        form = CommentForm
    context = {"form": form}
    template_name = 'add-comment.html'
    return render(request, template_name, context)
コード例 #24
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.author = request.user
            comment.author_id = request.user.id
            comment.save()
            return redirect("post_detail", pk=post.pk)
    else:
        form = CommentForm()
    return render(request, "add_comment_to_post.html", {"form": form})
コード例 #25
0
def comment_create(request, post_pk):
    if not request.user.is_authenticated():
        return redirect('member:login')
    post = get_object_or_404(Post, pk=post_pk)
    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()
            next = request.GET.get('next', '').strip()
            # post_list페이지 에서 댓글을 달더라도 post_create페이지로
            # 이동 하는 것이 아니라 post_list에서 바로 작성될 수 있도록 해주기 위해
            # 탬플릿의 form 태그에 get파라미터를 추가하고
            # 아래의 if 문으로 get 파라미터의 키 값인
            # next를 확인하해서 post_list로 리다이렉트 해준다.
            if next:
                return redirect(next)
            return redirect('post:post_detail', post_pk=post_pk)
コード例 #26
0
ファイル: views.py プロジェクト: FatmaTosun/MyBlog-CoolBlue
def post_detail(request,slug):
	post = get_object_or_404(Post, slug=slug)
	comments=Comment.objects.filter(content_type=
		ContentType.objects.get_for_model(Post), object_id=post.id)
	#ipdb.set_trace()

	form = CommentForm(user=request.user)

	if request.POST:
		form = CommentForm(request.POST, user=request.user)

		if form.is_valid():
			comment = form.save(commit=False)
			comment.content_type = ContentType.objects.get_for_model(Post)
			comment.object_id = post.id
			comment.post = post
			comment.save()

		return redirect(post.get_absolute_url())

	return render(request,'post/post_detail.html',
							  {'post': post,'form': form, 'comments':comments})
コード例 #27
0
ファイル: views.py プロジェクト: morningkyle/cms_site
def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post,
                             slug=post,
                             status='published',
                             publish__year=year,
                             publish__month=month,
                             publish__day=day)

    # List of similar posts
    post_tags_ids = post.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(
        id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by(
        '-same_tags', '-publish')[:4]

    # List of active comments for this post
    comments = post.comments.filter(active=True)
    if request.method == 'POST':
        # A comment was posted
        comment_form = CommentForm(data=request.POST)
        print(request.user)
        if comment_form.is_valid():
            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.post = post
            new_comment.name = request.user
            # Save the comment to the database
            new_comment.save()
            return HttpResponseRedirect(request.path)
    else:
        comment_form = CommentForm()
        return render(
            request, 'post/detail.html', {
                'post': post,
                'comments': comments,
                'comment_form': comment_form,
                'similar_posts': similar_posts
            })
コード例 #28
0
def post_comment(request):
    print("进入评论")
    post_id = request.POST.get('post_id')
    conent = request.POST.get('body')
    # print(post_id)
    article = get_object_or_404(Post, id=post_id)
    print(article)
    # 处理 POST 请求
    response = {'st':''}
    if request.method == 'POST':
        comment = CommentForm(request.POST)
        if comment.is_valid():
            new_com = comment.save(commit=False)
            new_com.post = article
            new_com.u_name = User.objects.get(id=request.session['id'])
            new_com.save()
            p = threading.Thread(target=tip,args=(article,post_id))
            p.start()
            try:
                print(request.session['id'],post_id)
                obj = Like.objects.get(u_name_id=request.session['id'],post_id=post_id)
                obj.comment = True
                obj.save()
            except Exception as e:
                print(e)
                print("生成新的用户操作")
                Like.objects.create(u_name_id=request.session['id'],post_id=post_id,collection=True)
            t = Comment.objects.filter(body=conent).first().created
            t = str(t)
            response['st'] = "<hr style='background-color: #f2dede;border: 0 none;color: #eee;height: 1px;'><div style='margin:10px 0 10px 0'><strong style='color: pink'>"+request.session['username']+"</strong> 于 <span style='color: green'>"+t[:t.find('.')]+"</span> 时说:<p style='font-family: inherit; font-size: 1em;'>"+conent+"</p></div>"
            return JsonResponse(response)
        else:
            return HttpResponse("表单内容有误,请重新填写。")
    # 处理错误请求
    else:
        return HttpResponse("发表评论仅接受POST请求。")