Exemplo n.º 1
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)
Exemplo n.º 2
0
    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['title'] = f'{self.object.name}'
        context['tags'] = get_all_tags(self.object.pk)
        if self.request.method == 'GET':
            context['comments'] = Comment.objects.filter(
                comment_post=self.kwargs['pk']).order_by('path')
            if self.request.user.is_authenticated:
                context['form'] = self.comment_form

        if self.request.method == 'POST':
            form = CommentForm(self.request.POST)
            if form.is_valid():
                comment = Comment(path=[],
                                  comment_post=self.object.pk,
                                  author=self.request.user,
                                  content=form.cleaned_data['comment_area'])
                comment.save()

                # сформируем path после первого сохранения
                # и пересохраним комментарий

                try:
                    comment.path.extend(
                        Comment.objects.get(
                            id=form.cleaned_data['parent_comment']).path)
                    comment.path.append(comment.id)
                    # print('получилось')
                except ObjectDoesNotExist:
                    comment.path.append(comment.id)
                    # print('не получилось')

                comment.save()

        return context
Exemplo n.º 3
0
def add_comment(request, pk):
    form = CommentForm(request.POST)
    post = get_object_or_404(Post, id=pk)

    if form.is_valid():
        comment = Comment()
        comment.path = []
        comment.comment_post = post
        comment.author = auth.get_user(request)
        comment.content = form.cleaned_data['comment_area']
        comment.save()

        # Django не позволяет увидеть ID комментария по мы не сохраним его,
        # сформируем path после первого сохранения
        # и пересохраним комментарий
        try:
            comment.path.extend(
                Comment.objects.get(
                    id=form.cleaned_data['parent_comment']).path)
            comment.path.append(comment.id)
        except ObjectDoesNotExist:
            comment.path.append(comment.id)

        comment.save()

    return redirect(comment.get_absolute_url())
Exemplo n.º 4
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)
Exemplo n.º 5
0
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("/")
Exemplo n.º 6
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)
Exemplo n.º 7
0
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
    })
Exemplo n.º 8
0
def comment_create(request, post_pk):
    if not request.user.is_authenticated:
        return redirect('member:login')
    # URL get parameter로 온 'post_pk'에 해당하는
    # Post instacne를 'post'변수에 할당
    # 찾지못하면 404Error를 브라우저에 리턴
    post = get_object_or_404(Post, pk=post_pk)
    if request.method == 'POST':
        # 데이터가 바인딩된 CommentForm인스턴스를 form에 할당
        form = CommentForm(request.POST)
        # 유효성 검증
        if form.is_valid():
            # 통과한 경우, Post에 해당하는 Comment 인스턴스 생성
            PostComment.objects.create(author=request.user,
                                       post=post,
                                       content=form.cleaned_data['content'])

            # post_list에서 오는 요청 처리
            next = request.GET.get('next')
            print(next)

            if next:
                return redirect(next)
            # 생성 후 Post의 detail화면으로 이동
            return redirect('post:post_detail', post_pk=post_pk)
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
def comment(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            aid = form.cleaned_data['aid']
            name = form.cleaned_data['name']
            content = form.cleaned_data['content']
            Comment.objects.create(aid=aid, name=name, content=content)
            return redirect('/post/article/?aid=%s' % aid)
    return redirect('/post/home/')
Exemplo n.º 11
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}
Exemplo n.º 12
0
def add_comment(request, article_id):
    form = CommentForm(request.POST)
    post = get_object_or_404(Post, id=article_id)

    if form.is_valid():
        comment = Comment()
        comment.path = []
        comment.post_id = post
        comment.author_id = auth.get_user(request)
        comment.content = form.cleaned_data['comment_area']
        comment.save()

    return redirect(post.get_absolute_url())
Exemplo n.º 13
0
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
                              })
Exemplo n.º 14
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)
Exemplo n.º 15
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)
Exemplo n.º 16
0
def comment_add(request, post_id):
    if request.method == 'POST':
        form = CommentForm(data=request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']
            # HttpRequest에는 항상 User정보가 전달된다
            user = request.user
            # URL인자로 전달된 post_id값을 사용
            post = Post.objects.get(id=post_id)
            # post의 메서드를 사용해서 Comment객체 생성
            post.add_comment(user, content)

        # 다시 해당하는 post_detail로 리다이렉트
        return redirect('post:list')
Exemplo n.º 17
0
def comment_add(request, post_id):
    if request.method == "POST":
        user = request.user
        form = CommentForm(data=request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']
            post = Post.objects.get(id=post_id)
            post.add_comment(user, content)
            return redirect('post:post-list')
        else:
            post = Post.objects.get(id=post_id)
            context = {
                'post': post
                # 'comment_list': Post.comment_set.all(),
            }
        return render(request, 'post/post-list.html', context)
Exemplo n.º 18
0
 def get_context_data(self, **kwargs):
     context = super(BlogDetailView, self).get_context_data(**kwargs)
     context['form'] = CommentForm()
     context['comments'] = Comments.objects.filter(post_id=self.kwargs.get(
         'post_id')).order_by('-created').select_related(
             'user').select_related('user__userdetails')
     return context
Exemplo n.º 19
0
def post_list(request):
    # 전체 Post목록 QuerySet생성 (아직 평가되지 않음)
    all_posts = Post.objects.all()
    # Paginator객체 생성, 한 페이지당 3개씩
    p = Paginator(all_posts, 3)

    # GET parameter에서 'page'값을 page_num변수에 할당
    page_num = request.GET.get('page')

    # Paginator객체에서 page메서드로 page_num변수를 인수로 전달하여 호출
    try:
        posts = p.page(page_num)

    # 만약 page_num변수가 int형으로 변환이 불가능하면
    except PageNotAnInteger:
        # 1페이지에 해당하는 Post object list를 posts에 할당
        posts = p.page(1)
    # 만약 page_num에 객체가 없을 경우 (빈 페이지)
    except EmptyPage:
        # 마지막 페이지에 해당하는 Post object list를 posts에 할당
        posts = p.page(p.num_pages)

    # render에 사용할 dict객체
    context = {
        'posts': posts,
        # 'comment_form': CommentForm(),
        'comment_form': CommentForm(auto_id=False),
    }
    return render(request, 'post/post_list.html', context)
Exemplo n.º 20
0
def post_list(request):
    # (0621) 위 post_list_original() 함수뷰에서 posts가 Paginator를 통해 5개씩 출력하도록 수정

    # 전체 Post 목록 QuerySet생성 (아직 평가되지 않은 상태)
    all_posts = Post.objects.all()

    # GET 파라미터에서 'page'값을 page_num 변수에 할당 (1. 오브젝트, 2. 개당 출력 갯수)
    paginator = Paginator(all_posts, 2)
    page = request.GET.get('page', 1)

    try:
        # Page형 오브제트를 돌려준다.
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    index = posts.number - 1
    max_index = len(paginator.page_range)
    start_index = index - 3 if index >= 3 else 0
    end_index = index + 3 if index <= max_index - 3 else max_index
    page_range = paginator.page_range[start_index:end_index]
    context = {
        'posts': posts,
        'page_range': page_range,
        'comment_form': CommentForm(),
    }

    return render(request, 'post/post_list.html', context)
Exemplo n.º 21
0
def post_list_original(request):
    posts = Post.objects.all()
    context = {
        'posts': posts,
        'comment_form': CommentForm(),
    }
    return render(request, 'post/post_list.html', context)
Exemplo n.º 22
0
def post_list(request):
    # 아직 평가되지 않은 전체 쿼리셋 들고오기
    all_posts = Post.objects.all()
    # Paginator를 사용하여 모든 포스트를 5개씩 페이지 분할한 후 paginator변수에 할당
    paginator = Paginator(all_posts, 5)

    # GET 파라미터에서 page의 value값을 page_num 변수에 할당
    page_num = request.GET.get('page')
    # paginator의 페이지번호가 page_num인 포스트들을 posts변수에 할당
    if page_num:
        posts = Post.objects.filter(page_num * 9).order_by('-created_date')
    elif not page_num:
        pass

    try:
        posts = paginator.page(page_num)
    # page_num이 숫자형이 아닐 경우에는 1번째 페이지의 posts을 가져옴
    except PageNotAnInteger:
        posts = paginator.page(1)
    # 해당페이지번호가 없을 경우에는 paginator의 마지막 페이지의 posts을 가져옴
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    # 예외처리해준 posts 변수와 comment_form을 렌더링시키기 위해 딕셔너리 삽입
    context = {
        'posts': posts,
        'comment_form': CommentForm(),
    }
    # post_list 템플릿에 만들어준 context dict를 넣어 렌더링함.
    return render(request, 'post/post_list.html', context)
Exemplo n.º 23
0
def post_detail(request, post_id):
    post = Post.objects.get(id=post_id)
    comment_form = CommentForm()
    context = {
        'post': post,
        'comment_form': comment_form,
    }
    return render(request, 'post/post_detail.html', context)
Exemplo n.º 24
0
def post_comment(request, post_id):
    p = Post.objects.get(id=post_id)
    current_user = request.user

    if not current_user.is_authenticated:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            c = Comment(post=p,
                        author=current_user,
                        date=datetime.now(),
                        content=form.cleaned_data['comment'])
            c.save()

    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Exemplo n.º 25
0
def view_post(request, post_id):
    post = Post.objects.get(id=post_id)
    if request.method == 'POST':
        form = CommentForm(data=request.POST)
        if form.is_valid():
            obj = Comment(
                author=request.user,
                post=post,
                comment=form.cleaned_data.get('comment'),
                timestamp=timezone.now(),
            )
            obj.save()

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

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

    return render(request, 'post.html', context)
Exemplo n.º 26
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
    })
Exemplo n.º 27
0
def post_list(request):
    posts = Post.objects.exclude(author__isnull=True)
    comment_form = CommentForm()

    context = {
        'posts': posts,
        'comment_form': comment_form,
    }

    return render(request, 'post/post_list.html', context)
Exemplo n.º 28
0
def post_detail(request, post_id):
    # 인자로 전달된 post_id와 일치하는 id를 가진 Post객체 하나만 조회
    post = Post.objects.get(id=post_id)
    # Comment를 생성할 Form객체를 생성, 할당
    comment_form = CommentForm()
    context = {
        'post': post,
        'comment_form': comment_form,
    }
    return render(request, 'post/post_detail.html', context)
Exemplo n.º 29
0
    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']}))
Exemplo n.º 30
0
def add_Comment(request, article_id):
    form = CommentForm(request.POST)
    article = get_object_or_404(Article, id=article_id)
    if form.is_valid():
        comment = Comment()
        comment.path = []
        comment.article_id = article
        comment.author_id = auth.get_user(request)
        comment.content = form.cleaned_data['comment_area']
        comment.save()
        try:
            comment.path.extend(
                Comment.objects.get(
                    id=form.cleaned_data['parent_comment']).path)
            comment.path.append(comment.id)
        except ObjectDoesNotExist:
            comment.path.append(comment.id)
        comment.save()

    return redirect(article.get_absolute_url())
Exemplo n.º 31
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)
Exemplo n.º 32
0
def post_list_original(request):
    # 모든 Post목록을 'posts'라는 key로 context에 담아 return render처리
    # post/post_list.html을 template으로 사용하도록 한다

    # 각 포스트에 대해 최대 4개까지의 댓글을 보여주도록 템플릿에 설정
    posts = Post.objects.all()
    context = {
        'posts': posts,
        'comment_form': CommentForm(),
    }
    return render(request, 'post/post_list.html', context)
Exemplo n.º 33
0
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})
Exemplo n.º 34
0
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=[]))