예제 #1
0
파일: views.py 프로젝트: DannyCork/demozoo
class AddCommentView(TemplateView):
	@method_decorator(writeable_site_required)
	@method_decorator(login_required)
	def dispatch(self, request, *args, **kwargs):
		commentable_id = self.args[0]
		self.commentable = get_object_or_404(self.commentable_model, id=commentable_id)
		self.comment = Comment(commentable=self.commentable, user=request.user)
		return super(AddCommentView, self).dispatch(request, *args, **kwargs)

	def get(self, request, *args, **kwargs):
		self.form = CommentForm(instance=self.comment, prefix='comment')
		context = self.get_context_data()
		return self.render_to_response(context)

	def post(self, request, *args, **kwargs):
		self.form = CommentForm(request.POST, instance=self.comment, prefix='comment')
		if self.form.is_valid():
			self.form.save()
			return redirect(
				self.commentable.get_absolute_url() + ('#comment-%d' % self.comment.id)
			)
		else:
			context = self.get_context_data()
			return self.render_to_response(context)

	def get_context_data(self, **kwargs):
		context = super(AddCommentView, self).get_context_data(**kwargs)
		context['commentable'] = self.commentable
		context['commentable_name'] = self.get_commentable_name(self.commentable)
		context['comment_form'] = self.form
		context['submit_action'] = self.submit_action
		return context

	template_name = 'comments/add_comment.html'
예제 #2
0
def process_post_add_comment(request, context, datapackage,
                             force_anonymous_user, success_view_name,
                             failure_template_name):
    if force_anonymous_user:
        person = None
    else:
        person = Person.objects.get(user=request.user)

    comment_form = CommentForm(request.POST,
                               datapackage_id=datapackage.id,
                               person=person)

    if comment_form.is_valid():
        comment_form.save()
        messages.success(request, 'Comment saved')
        return redirect(
            reverse(success_view_name, kwargs={'uuid': datapackage.uuid}))

    else:
        messages.error(
            request,
            'Error saving the comment. Check below for the error messages')
        context['comment_form'] = comment_form

        return render(request, failure_template_name, context)
예제 #3
0
    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data(*args, **kwargs)

        post_id = (
            self.kwargs['year'],
            self.kwargs['month'],
            self.kwargs['day'],
            self.kwargs['slug'],
        )

        try:
            obj = self.pseudo_model.get_object(post_id)
        except KeyError:
            raise Http404

        context['obj'] = obj
        context['comments'] = Comment.objects.filter(url=obj.url)

        if self.request.method == 'POST':
            form = CommentForm(self.request.POST, obj=obj, request=self.request)

            if form.is_valid():
                form.save()
                messages.success(self.request, 'Your comment has been posted.')
        else:
            form = CommentForm()

        context['form'] = form
        context['ONE_YEAR_TIMEOUT'] = ONE_YEAR_TIMEOUT

        return context
예제 #4
0
def detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    tags = Tag.objects.all()
    liked_posts = (Post.objects.all().annotate(
        likes_count=Count("like")).order_by("-likes_count"))
    categories = Category.objects.all()
    context = {
        "post": post,
        "categories": categories,
        "tags": tags,
        "liked_posts": liked_posts
    }

    if request.method == "POST":
        comment = request.POST.copy()
        comment['post'] = post.id
        if request.user:
            comment['user'] = request.user.id
        form = CommentForm(comment)
        if form.is_valid():
            # some logic
            form.save()
            return redirect('blog:post_detail', pk)
    else:
        form = CommentForm()

    context['form'] = form
    return render(request, "core/detail.html", context)
예제 #5
0
class AddCommentView(TemplateView):
    @method_decorator(writeable_site_required)
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        commentable_id = self.args[0]
        self.commentable = get_object_or_404(self.commentable_model, id=commentable_id)
        self.comment = Comment(commentable=self.commentable, user=request.user)
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        self.form = CommentForm(instance=self.comment, prefix='comment')
        context = self.get_context_data()
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        self.form = CommentForm(request.POST, instance=self.comment, prefix='comment')
        if self.form.is_valid():
            self.form.save()
            return redirect(
                self.commentable.get_absolute_url() + ('#comment-%d' % self.comment.id)
            )
        else:
            context = self.get_context_data()
            return self.render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['commentable'] = self.commentable
        context['commentable_name'] = self.get_commentable_name(self.commentable)
        context['comment_form'] = self.form
        context['submit_action'] = self.submit_action
        return context

    template_name = 'comments/add_comment.html'
예제 #6
0
def create_comment(request, slug=None):
    try:
        instance = Post.objects.get(slug=slug)
    except ObjectDoesNotExist:
        instance = None
    form = CommentForm(request.POST or None)
    print('The form data :', form)
    if form.is_valid():
        print(form.cleaned_data)
        form_data = form.save(commit=False)
        form_data.user = request.user
        form_data.content_type = instance.get_content_type
        form_data.object_id = instance.id
        form_data.parent = 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()
                print('parent_obj :',parent_obj)
                form_data.parent = parent_obj
        form.save()
        messages.success(request, 'form has being submitted')
        return HttpResponseRedirect(instance.get_absolute_url())
    else:
        messages.error(request, f'{form.errors}')
    return redirect('blog:blog_detail', instance.slug)
예제 #7
0
def process_post_add_comment(request, context, datapackage,
                             force_anonymous_user, success_view_name,
                             failure_template_name):
    if force_anonymous_user:
        logged_user = None
    else:
        logged_user = request.user

    comment_form = CommentForm(request.POST,
                               datapackage_id=datapackage.id,
                               logged_user=logged_user,
                               allow_private=True)

    if comment_form.is_valid():
        comment_form.save()
        messages.success(request, 'Comment saved')
        return redirect(
            reverse(success_view_name, kwargs={'uuid': datapackage.uuid}))

    else:
        messages.error(
            request,
            'Error saving the comment. Check below for the error messages')
        context['comment_form'] = comment_form
        context['datapackage'] = datapackage

        return render(request, failure_template_name, context)
예제 #8
0
def comment_new(request):
    if request.method == 'POST':
        id = request.POST['user_id']
        #subject = request.POST['title']
        user = request.POST['username']
        # last_name = request.POST['last_name']

        #lastname = request.POST['lastname']
        print('ITEMS')
        for key, value in request.POST.items():
            print(str(key) + "--")
            print(str(value))
        form = CommentForm(request.POST, request.FILES)
        #     print formset.errors

        if form.is_valid():
            form.save()

    # send_mail("[ENGLISH] " + subject,user +" "+ last_name + " said  "+ message + " on http://english.darwoft.com:8000", '*****@*****.**',
    #     ['*****@*****.**'], fail_silently=False)

    posts = Post.objects.all().order_by('-created')
    return render(request,
                  os.path.join(BASE_DIR, 'templates', 'posts', 'feed.html'),
                  {'posts': posts})
예제 #9
0
파일: views.py 프로젝트: bagainu/noproject
def detail(request, blog_id):
    post = get_object_or_404(Post, pk=blog_id)
    if request.method == 'POST' and request.user.is_authenticated:
        comment_form = CommentForm(request.POST, request.FILES)
        if comment_form.is_valid():
            comment_instance = comment_form.save(commit=False)
            comment_instance.comment_user = request.user
            comment_instance.content_type = ContentType.objects.get_for_model(Post)
            comment_instance.content_object = post
            comment_instance.object_id = post.id
            parent_id = request.POST.get('parent_id')
            if parent_id is not None:
                comment_instance.parent_comment = Comment.objects.get(pk=int(parent_id))
            comment_form.save()
            comment_form.save_m2m()
            return HttpResponseRedirect(post.get_absolute_url())

    post_comments = post.blog_comment.filter(parent_comment=None).order_by('-comment_date_time')
    page_post_comments = page_list(request, post_comments, 10)
    context = {
        'booklog': post.content_object,
        'post': post,
        'post_comments': page_post_comments,
        'comment_form': CommentForm(),
    }
    return render(request, 'blog/detail.html', context)
def ticket_detail(request, pk):
    ticket = get_object_or_404(Ticket, pk=pk)
    user = request.user
    comments = Comment.objects.filter(ticket=ticket)
    if request.method == 'POST':
        if user.is_authenticated:
            comment_form = CommentForm(request.POST)
            if comment_form.is_valid():
                comment_form.instance.user = user
                comment_form.instance.ticket = ticket
                comment_form.save()
                return redirect('ticket-detail', pk)
            else:
                comment_form = CommentForm()
        else:
            messages.error(request, 'Please login to comment')
            comment_form = CommentForm()
    else:
        comment_form = CommentForm()
    return render(
        request, 'main/ticket_detail.html', {
            "object": ticket,
            "pk": pk,
            "comments": comments,
            'comment_form': comment_form
        })
예제 #11
0
파일: views.py 프로젝트: HughMcGrade/eusay
def edit_comment(request, comment_id):
    if not request.user.is_authenticated():
        return request_login(request)
    try:
        comment = Comment.objects.get(id=comment_id)
    except:
        raise Http404
    if not request.user == comment.user:
        messages.add_message(request,
                             messages.ERROR,
                             "You can only edit your own comments.")
        return HttpResponseRedirect(reverse('proposal',
                                            args=[
                                                str(comment.proposal.id),
                                                comment.proposal.slug
                                            ]))
    else:
        if request.method == "POST":
            if comment.is_new():
                form = CommentForm(request.POST, instance=comment)
                if form.is_valid():
                    form.save()
                    messages.add_message(request,
                                         messages.SUCCESS,
                                         "Comment edited.")
                    return HttpResponseRedirect(reverse("proposal", args=[
                        str(comment.proposal.id), comment.proposal.slug
                    ]) + "#comment_" + str(comment.id))
                else:
                    messages.add_message(request,
                                         messages.ERROR,
                                         "Invalid comment")
            else:
                messages.add_message(request,
                                     messages.ERROR,
                                     "You can only edit a comment in the "
                                     "first 5 minutes.")
        form = CommentForm(instance=comment)
        if comment.is_new():
            if request.is_ajax():
                extend_template = "ajax_base.html"
            else:
                extend_template = "base.html"
            return render(request,
                          "edit_comment_form.html",
                          {"form": form,
                           "comment": comment,
                           "extend_template": extend_template})
        else:
            messages.add_message(request,
                                 messages.ERROR,
                                 "You can only edit a comment in the "
                                 "first 5 minutes.")
            return HttpResponseRedirect(reverse("proposal", args=[
                str(comment.proposal.id), comment.proposal.slug
            ]) + "#comment_" + str(comment.id))
예제 #12
0
def update(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("%s#%s" % (
                comment.link.get_absolute_url(), comment.id))
        else:
            print form.errors
예제 #13
0
파일: views.py 프로젝트: m0rfey/myblog
def add_comment(request, article_id):
    if request.POST and ("pause", not request.session):
        form = CommentForm(request.POST)
        return_path = request.META.get('HTTP_REFERER', '/')
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comment_user = request.user
            comment.comment_article = Article.objects.get(id=article_id)
            form.save()
            request.session.set_expiry(600)
            request.session['pause'] = True
    return redirect(return_path)
예제 #14
0
파일: views.py 프로젝트: maximchuk/myblog
def add_comment(request, article_id):
    if request.POST and ("pause", not request.session):
        form = CommentForm(request.POST)
        return_path = request.META.get('HTTP_REFERER', '/')
        if form.is_valid():
            comment = form.save(commit=False)
            comment.comment_user = request.user
            comment.comment_article = Article.objects.get(id = article_id)
            form.save()
            request.session.set_expiry(600)
            request.session['pause'] = True
    return  redirect(return_path)
예제 #15
0
파일: views.py 프로젝트: adoleba/blog
def post_detail(request, year, month, day, slug):
    post = get_object_or_404(Post,
                             slug=slug,
                             status='published',
                             published__year=year,
                             published__month=month,
                             published__day=day)
    categories = post.category.all()
    comments = post.comments.filter(parent__isnull=True).order_by('-created')

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            parent_obj = None

            try:
                parent_id = int(request.POST.get('parent_id'))
            except:
                parent_id = None

            if parent_id:
                parent_obj = PostComment.objects.get(id=parent_id)
                if parent_obj:
                    replay_comment = comment_form.save(commit=False)
                    replay_comment.parent = parent_obj

            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
            return redirect(request.path)
    else:
        comment_form = CommentForm()

    try:
        previous_post = post.get_previous_by_published()
    except post.DoesNotExist:
        previous_post = post

    try:
        next_post = post.get_next_by_published()
    except post.DoesNotExist:
        next_post = post

    return render(
        request, 'posts/post_detail.html', {
            'post': post,
            'categories': categories,
            'comment_form': comment_form,
            'comments': comments,
            'previous_post': previous_post,
            'next_post': next_post
        })
예제 #16
0
def create_comment(request):
    """Create comment view."""
    if request.method == 'POST':
        form = CommentForm(None, data=request.POST)
        if form.is_valid():
            with transaction.atomic():
                comment = form.save(commit=False)
                comment.user = request.user
                comment.content = json.loads(form.cleaned_data.get('content'))[
                    'html']  # Quill form field's html
                form.save()
                create_notification(request, form)
                run_reputation_update(request.user)
        return redirect('post', pk=request.POST['post'])
예제 #17
0
def addcomment(request, talent_id):
    if request.POST and ("pause" not in request.session):
        # sozdaem formu-->raznosim v nee dannie is post zaprosa
        form = CommentForm(request.POST)
        # esli forma validna
        if form.is_valid():
            # zapret auti sohraneniya formi
            comment = form.save(commit=False)
            # nahodim, k kakomu talantu sohranit'
            comment.comments_talent = Talent.objects.get(id=talent_id)
            comment.comments_from = request.user
            form.save()
        # request.session.set_expiry(60)
        # request.session['pause'] = True
    return redirect('/talents/get/%s/' % talent_id)
예제 #18
0
파일: views.py 프로젝트: asbjornu/demozoo
class EditCommentView(TemplateView):
    @method_decorator(writeable_site_required)
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        commentable_id = self.args[0]
        comment_id = self.args[1]

        commentable_type = ContentType.objects.get_for_model(
            self.commentable_model)
        self.commentable = get_object_or_404(self.commentable_model,
                                             id=commentable_id)
        self.comment = get_object_or_404(Comment,
                                         id=comment_id,
                                         content_type=commentable_type,
                                         object_id=commentable_id)

        if not request.user.is_staff:
            return redirect(self.comment.get_absolute_url())

        return super(EditCommentView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        self.form = CommentForm(instance=self.comment, prefix='comment')
        context = self.get_context_data()
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        self.form = CommentForm(request.POST,
                                instance=self.comment,
                                prefix='comment')
        if self.form.is_valid():
            self.form.save()
            return redirect(self.comment.get_absolute_url())
        else:
            context = self.get_context_data()
            return self.render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super(EditCommentView, self).get_context_data(**kwargs)
        context['commentable'] = self.commentable
        context['commentable_name'] = self.get_commentable_name(
            self.commentable)
        context['comment'] = self.comment
        context['comment_form'] = self.form
        context['submit_action'] = self.submit_action
        return context

    template_name = 'comments/edit_comment.html'
예제 #19
0
파일: views.py 프로젝트: mrigor/blogly
def blog(request, slug):
    from comments.models import BLOG
    blog = Blog.objects.get(slug=slug)
    if not blog:
        raise Http404
    form = CommentForm()
    if request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.thing_id = blog.id
            comment.type = BLOG
            comment.thread_id, comment.reverse_thread_id = \
                    get_thread_id(type='blog', thing_id=blog.id)
            comment.save()
            return HttpResponseRedirect(reverse(
                'blog.views.blog',
                args=(blog.slug,)))

    commentsPage, commentsIndex, commentsTree = \
        get_comments_page(request, type=BLOG, obj=blog, rpp=10)

    return render_to_response(request, 'blog/blog.html', {
        'blog': blog,
        'commentForm': form,
        'comments': commentsPage,
        'commentsIndex': commentsIndex,
        'commentsTree': commentsTree,
    })
예제 #20
0
def detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if post.draft:
        if post.user != request.user:
            messages.error(request,'you have not permission to see that post',extra_tags='alert alert-danger')
            return redirect('posts:index')
    form=CommentForm(request.POST or None)
    # add comment
    if form.is_valid() and request.user.is_authenticated:
        instance=form.save(commit=False)
        instance.user=request.user
        instance.post=post
        parent=None
        try:
            parent_id=int(request.POST.get('parent_id'))
        except:
            parent_id=None
        if parent_id:
            query=Comment.objects.filter(id=parent_id)
            if query.exists():
                parent=query.first()
        instance.parent=parent
        instance.save()
        return redirect('posts:detail',pk)
    return render(request, 'detail.html', {'post': post,'comment_form':form})
예제 #21
0
class NewsDetail(DetailView):
    model = Article
    template_name = 'news/article.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.comment_form = CommentForm(request.POST or None) # create filled (POST) or empty form (initial GET)
        if request.method == 'POST':
            self.comment_form.instance.article_id = self.get_object().id

            if self.comment_form.is_valid():
                comment = self.comment_form.save(commit=True)
                client = Client()
                client.publish(self.get_object().get_cent_comments_channel_name(), comment.as_compact_dict())
                cent_response = client.send()
                print('sent to channel {}, got response from centrifugo: {}'.format(self.get_object().get_cent_comments_channel_name(),
                                                                                    cent_response))
                return HttpResponse()
                # return HttpResponseRedirect(reverse('news:detail', args=[self.get_object().pk,]))
            else:
                return super().get(request, *args, **kwargs)
                # context = self.get_context_data()
                # return render('news/article.html', context)

        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comment_form'] = self.comment_form
        return context
예제 #22
0
파일: views.py 프로젝트: vitorh45/exemplos
def post_show(request, blog, slug):    
    try:
        blog = Blog.objects.get(slug=blog)
    except:
        raise Http404(u'Não disponível')
    try:
        post = Post.published.get(slug=slug, blog=blog)
    except:
        raise Http404(u'Não disponível')    

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.submit_date = datetime.now()
            comment.user = None
            comment.site = Site.objects.get_current()
            comment.ip_address = request.META.get("REMOTE_ADDR", None)
            comment.content_type = ContentType.objects.get_for_model(post)
            comment.object_pk = post.id
            comment.save()
            return HttpResponseRedirect(reverse('post_show',args=(blog.slug,post.slug)))
    else:
        form = CommentForm()

    return render_to_response('blog/post_show.html', {
        'post': post,
        'blog': blog,
        'form':form,
    }, context_instance=RequestContext(request))
예제 #23
0
파일: views.py 프로젝트: winglq/site
 def post(self, request, pk):
     self.object = get_object_or_404(Article, id=pk)
     comment = CommentForm(request.POST)
     commit_instance = comment.save()
     self.object.comments.add(commit_instance)
     self.object.save()
     return redirect(reverse('article_detail', args=[pk]))
예제 #24
0
def edit_comment(request, problem_id, solution_id, comment_id):
    solution = Solution.objects.get(pk=solution_id)
    try:
        comment = Comment.objects.get(pk=comment_id)
        if comment.user.email != request.session['email']:
            return HttpResponseRedirect('/problems/'+str(problem_id)+'/show_solution/'+str(solution_id))
    except Comment.DoesNotExist:
        raise Http404("Comment does not exist")
    if request.method == 'POST':
        comment_form = CommentForm(request.POST, instance=comment)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.user = UserProfile.objects.get(email=request.session['email'])
            comment.save()
            solution.comments.add(comment)
            return HttpResponseRedirect('/problems/'+str(problem_id)+'/show_solution/'+str(solution_id))
        else:
            print comment_form.errors
    elif request.method == 'GET':
        c_edit = comment
        # c_edit.content = bleach.clean(c_edit.content, strip=True)
        comment_form = CommentForm(instance=c_edit)

        return render(request, 'problems/edit_comment.html',
                      {'form': comment_form, 'problem_id': problem_id, 'solution_id': solution_id, 'comment':comment})
예제 #25
0
def edit_comment(request, sub_id, comment_id):
    submission = Submission.objects.get(pk=sub_id)
    try:
        comment = Comment.objects.get(pk=comment_id)
        if comment.user.email != request.session['email']:
            return HttpResponseRedirect('/submissions/show/'+str(sub_id))
    except Comment.DoesNotExist:
        raise Http404("Comment does not exist")
    if request.method == 'POST':
        comment_form = CommentForm(request.POST, instance=comment)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.user = UserProfile.objects.get(email=request.session['email'])
            # comment.content = bleach.clean(comment.content, strip=True)
            # comment.content = markdown.markdown(comment.content)
            comment.save()
            submission.comments.add(comment)
            return HttpResponseRedirect('/submissions/show/' + str(sub_id))
        else:
            raise Http404("Form is not valid")
    elif request.method == 'GET':
        c_edit = comment
        # c_edit.content = bleach.clean(c_edit.content, strip=True)
        comment_form = CommentForm(instance=c_edit)

        return render(request, 'submissions/edit_comment.html',
                      {'form': comment_form, 'sub_id': sub_id, 'comment':comment})
예제 #26
0
파일: views.py 프로젝트: vitorh45/exemplos
def article_show(request, channel, slug):
    try:
        article = Article.published_detail.get(slug=slug, channel__slug=channel)
        article.views_count_last_week += 1
        article.views_count += 1
        article.save()
    except:
        raise Http404(u'Notícia não encontrada')
    
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.submit_date = datetime.now()
            comment.user = None
            comment.site = Site.objects.get_current()
            comment.ip_address = request.META.get("REMOTE_ADDR", None)
            comment.content_type = ContentType.objects.get_for_model(article)
            comment.object_pk = article.id
            comment.save()
            return HttpResponseRedirect(reverse('article_show',args=(article.channel.slug,article.slug)))
    else:
        form = CommentForm()

    related_articles = article.get_related_articles()
    return render_to_response('articles/article_show.html', {
        'article': article,
        'related_articles': related_articles,
        'form':form,
        'is_article':True,
    }, context_instance=RequestContext(request))
예제 #27
0
def post_comment(request, post_pk):
    post = get_object_or_404(Post, pk=post_pk)

    # 判断用户的post请求,接收到时则处理表单数据
    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)  # commit=False,暂不保存
            comment.post = post
            comment.save()

            # 重定向到 post 的详情页,实际上当 redirect 函数接收一个模型的实例时,它会调用这个模型实例的 get_absolute_url 方法,
            # 然后重定向到 get_absolute_url 方法返回的 URL。
            return redirect(post)

        else:
            comment_list = post.comment_set.all()
            context = {
                'post': post,
                'form': form,
                'comment_list': comment_list
            }
            return render(request, 'blog/detail.html', context=context)
    # 不是 post 请求,说明用户没有提交数据,重定向到文章详情页。
    return redirect(post)
예제 #28
0
파일: views.py 프로젝트: begor/vas3k.club
def edit_comment(request, comment_id):
    comment = get_object_or_404(Comment, id=comment_id)

    if not request.me.is_moderator:
        if comment.author != request.me:
            raise AccessDenied()

        if not comment.is_editable:
            raise AccessDenied(
                title="Этот комментарий больше нельзя редактировать")

        if not comment.post.is_visible or not comment.post.is_commentable:
            raise AccessDenied(title="Комментарии к этому посту были закрыты")

    post = comment.post

    if request.method == "POST":
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.is_deleted = False
            comment.html = None  # flush cache
            comment.ipaddress = parse_ip_address(request)
            comment.useragent = parse_useragent(request)
            comment.save()
            return redirect("show_comment", post.slug, comment.id)
    else:
        form = CommentForm(instance=comment)

    return render(request, "comments/edit.html", {
        "comment": comment,
        "post": post,
        "form": form
    })
예제 #29
0
파일: views.py 프로젝트: miyaTest0001/tear
def comment(request, post_pk):
    # 先获取被评论的文章,因为后面需要把评论和被评论的文章关联起来
    post = get_object_or_404(Post, pk=post_pk)

    form = CommentForm(request.POST)

    if form.is_valid():
        #  commit=False 的作用是仅仅利用表单的数据生成 Comment 模型类的实例,但还不保存评论数据到数据库。
        comment = form.save(commit=False)

        comment.post = post

        comment.save()

        messages.add_message(request,
                             messages.SUCCESS,
                             '评论发表成功!',
                             extra_tags='success')

        return redirect(post)

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

    messages.add_message(request,
                         messages.ERROR,
                         '评论发表失败!请修改表单中的错误后重新提交。',
                         extra_tags='danger')

    return render(request, 'comments/preview.html', context=context)
예제 #30
0
def comment(request, post_pk):
    # 先获取被评论的文章,因为后面需要把评论和被评论的文章关联起来。
    # 这里我们使用了 django 提供的一个快捷函数 get_object_or_404,
    # 这个函数的作用是当获取的文章(Post)存在时,则获取;否则返回 404 页面给用户。
    post = get_object_or_404(Post, pk=post_pk)

    # django 将用户提交的数据封装在 request.POST 中,这是一个类字典对象。
    # 我们利用这些数据构造了 CommentForm 的实例,这样就生成了一个绑定了用户提交数据的表单。
    form = CommentForm(request.POST)

    # 当调用 form.is_valid() 方法时,django 自动帮我们检查表单的数据是否符合格式要求。
    if form.is_valid():
        # 检查到数据是合法的,调用表单的 save 方法保存数据到数据库,
        # commit=False 的作用是仅仅利用表单的数据生成 Comment 模型类的实例,但还不保存评论数据到数据库。
        comment = form.save(commit=False)

        # 将评论和被评论的文章关联起来。
        comment.post = post

        # 最终将评论数据保存进数据库,调用模型实例的 save 方法
        comment.save()
        messages.add_message(request, messages.SUCCESS, '评论发表成功!', extra_tags='success')
        # 重定向到 post 的详情页,实际上当 redirect 函数接收一个模型的实例时,它会调用这个模型实例的 get_absolute_url 方法,
        # 然后重定向到 get_absolute_url 方法返回的 URL。
        return redirect(post)

    # 检查到数据不合法,我们渲染一个预览页面,用于展示表单的错误。
    # 注意这里被评论的文章 post 也传给了模板,因为我们需要根据 post 来生成表单的提交地址。
    context = {
        'post': post,
        'form': form,
    }
    messages.add_message(request, messages.ERROR, '评论发表失败!请修改表单中的错误后重新提交。', extra_tags='danger')
    return render(request, 'comments/preview.html', context=context)
예제 #31
0
def PostDetail(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    user = request.user
    is_favorite = False
    comments = Comment.objects.filter(post=post).order_by('date')
    # checks to see if you've bookmarked the post and use flag for color change of button
    if request.user.is_authenticated:
        profile = Profile.objects.get(user=user)

        if profile.favorites.filter(id=post_id).exists(
        ):  # using this boolean flag to identify if post is bookmarked
            is_favorite = True
    # adds comment section to post detail view

    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()

    template = loader.get_template('post_detail.html')
    context = {
        'post': post,
        'is_favorite': is_favorite,
        'profile': profile,
        'form': form,
        'comments': comments,
    }
    return HttpResponse(template.render(context, request))
예제 #32
0
def post_comment(request, post_pk):
    # 获得该评论的文章
    post = get_object_or_404(Post, pk=post_pk)
    print(post.tags)
    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            # 将评论和文章关联起来
            comment.post = post
            comment.save()
            # 当表单的数据合法时 重定向到post的详情页
            # 当redirect 函数接收一个模型的实例时, 会调用这个模型实例的get_absolute_url方法
            # 这个方法会返回一个url 然后重定向到这个url
            return redirect(post)
        else:
            #
            comment_list = post.comment_set.all()
            context = {
                'post': post,
                'form': form,
                'comment_list': comment_list
            }
            print(post.tags)
            # 当表单数据不合法时,
            return render(request, 'blog/detail.html', context=context)
    return redirect(post)
예제 #33
0
파일: views.py 프로젝트: bagainu/noproject
 def post(self, request, booklog_id):
     booklog = get_object_or_404(BookLog, pk=booklog_id)
     comment_form = CommentForm(request.POST, request.FILES)
     if comment_form.is_valid():
         comment_instance = comment_form.save(commit=False)
         comment_instance.comment_user = request.user
         comment_instance.content_type = ContentType.objects.get_for_model(BookLog)
         comment_instance.content_object = booklog
         comment_instance.object_id = booklog.id
         parent_id = request.POST.get('parent_id')
         if parent_id is not None:
             comment_instance.parent_comment = Comment.objects.get(pk=int(parent_id))
         comment_form.save()
         comment_form.save_m2m()
         return HttpResponseRedirect(booklog.get_absolute_url())
     return self.get(request, booklog_id)
예제 #34
0
파일: views.py 프로젝트: Mrk2239/KProject
def post_comment(request,pk):
    post = get_object_or_404(Post,pk=pk)
    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            #comment.post = post
            comment.post_id = pk
            comment.save()
        #数据有误,需保存form表单所写的数据
        else:

            comment_list = post.comment_set.all()
            context = {
                'post':post,
                'form':form,
                'comment_list':comment_list,
            }

            return render(request,'blog/detail.html',context=context)

    #return redirect(reverse('blog:post_detail',kwargs={'pk':pk}))
    return redirect(post)
예제 #35
0
def post_comment(request, post_pk):

    # 先获取被评论的文章,因为后面需要把评论和被评论的文章关联起来
    # 这里我们使用了Django提供的一个快捷函数 get_object_or_404 页面给用户
    # 这个函数的作用是当前获取的文章(post)存在时,则获取;否则返回404页面给用户
    post = get_object_or_404(Post, pk=post_pk)
    # HTTP 请求有get和POST两种,一般用户通过表单提交数据都是通过post请求

    if request.method == 'POST':
        # 用户提交的数据存在request.POST中,这是一个类字典对象
        form =  CommentForm(request.POST)
        if form.is_valid():
            # 检查到数据是合法的,调用表单的 save 方法保存数据到数据库,
            # commit=False 的作用是仅仅利用表单的数据生成 Comment 模型类的实例,但还不保存评论数据到数据库。
            comment = form.save(commit=False)
            # 将评论和被评论的文章关联起来。
            comment.post = post
            # 最终将评论数据保存进数据库,调用模型实例的 save 方法
            comment.save()
            # 重定向到 post 的详情页,实际上当 redirect 函数接收一个模型的实例时,它会调用这个模型实例的 get_absolute_url 方法,
            # 然后重定向到 get_absolute_url 方法返回的 URL。
            return redirect(post)

        else:
            # 使用 post.comment_set.all() 反向查询全部评论。
            comment_list = post.comment_set.all()
            return render(request,'detail.html', locals())
        return redirect(post)
예제 #36
0
def add(request):
    data = {}
    user = request.user
    comment_form = CommentForm(data=request.POST)
    if not comment_form.is_valid():
        data['message'] = 'Form not valid!'
    else:
        try:
            post_id = int(request.POST.get('post_id', None))
        except(TypeError, ValueError, OverflowError):
            post_id = None
            data['message'] = 'Wrong post id'
        if post_id:
            try:
                post = Post.objects.get(id=post_id)
            except post.DoesNotExist:
                post = None
                data['message'] = 'Post doesn\'t exist'
            if post:
                # 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.user = user
                # Save the comment to the database
                new_comment.save()
                data['success'] = True
    return JsonResponse(data)
예제 #37
0
파일: views.py 프로젝트: vitorh45/exemplos
def video_show(request, slug):
    try:
        video = Video.objects.get(slug=slug)
    except:
        raise Http404(u'Vídeo não encontrado.')

    related_videos = video.get_related_videos()

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.submit_date = datetime.now()
            comment.user = None
            comment.site = Site.objects.get_current()
            comment.ip_address = request.META.get("REMOTE_ADDR", None)
            comment.content_type = ContentType.objects.get_for_model(video)
            comment.object_pk = video.id
            comment.save()
            return HttpResponseRedirect(reverse('video_show',args=[video.slug]))
    else:
        form = CommentForm()

    return render_to_response('videos/video_show.html', {
        'video': video,
        'related_videos':related_videos,
        'form':form,
    }, context_instance=RequestContext(request))
예제 #38
0
파일: views.py 프로젝트: cuiy0006/Bloggy
def post_comment(request):
    redirect_to = request.POST.get('next', request.GET.get('next', ''))
    postId = request.POST['postId']
    post = get_object_or_404(Post, pk=postId)

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            commenterId = request.user.pk
            commenter = get_object_or_404(User, pk=commenterId)
            comment.post = post
            comment.commenter = commenter
            comment.save()

            underId = request.POST['underId']
            replyToId = request.POST['replyToId']
            comment_ext_form = CommentExtensionForm(request.POST)
            if underId != '' and comment_ext_form.is_valid():
                comment_ext = comment_ext_form.save(commit=False)
                comment_ext.comment = comment

                under = get_object_or_404(Comment, pk=underId)
                replyTo = get_object_or_404(Comment, pk=replyToId)
                comment_ext.under = under
                comment_ext.replyTo = replyTo
                comment_ext.save()
    return redirect(post)
예제 #39
0
def add_comment(request, object_type, id):
    
    skip = False
    if object_type == 'comicpage':
        object = get_object_or_404(ComicPage, pk=id)
    elif object_type == 'article':
        object = get_object_or_404(Article, pk=id)
    elif object_type == 'profile':
        object = get_object_or_404(Profile, pk=id)
        friend_status = get_relationship_status(object.user, request.user)
        if friend_status < 2 and object.user != request.user:
            skip = True
    elif object_type == 'tutorial': 
        object = get_object_or_404(Tutorial, pk=id)
    elif object_type == 'episode': 
        object = get_object_or_404(Episode, pk=id)
    elif object_type == 'video': 
        object = get_object_or_404(Video, pk=id)
    if request.method == 'POST' and not skip:
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.save()
            object.comments.add(comment)
    comments = object.comments.filter(is_deleted=False)
    return render_to_response('comments/list.html', {'comments':comments}, context_instance=RequestContext(request))
예제 #40
0
파일: views.py 프로젝트: dwbaron/web
def post_comment(request, post_pk):
    post = get_object_or_404(Post, pk=post_pk)

    if request.method == 'POST':
        # 提交的表单在request.POST里面
        form = CommentForm(request.POST)

        if form.is_valid():
            # 用表单数据生成Comment类的实例,不保存到数据库
            # 因为只有form定义的字段
            comment = form.save(commit=False)

            comment.post = post

            comment.save()

            return redirect(post)

        else:
            # 反向查找所有评论
            comment_list = post.comment_set.all()

            context = {
                'post': post,
                'form': form,
                'comment_list': comment_list
            }

            return render(request, 'dw_blog/detail.html', context=context)
    # 不是post请求, 没有提交数据
    # 如果只返回模型实例,那么这个模型必须实现get_absolute_url方法
    return redirect(post)
예제 #41
0
def new(request, pk):
    note = get_object_or_404(Note, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.note = note
            comment.user = request.user
            comment.save()
            # add rep
            add_rep(request, c=comment)
            # create notification
            notify(comment=comment)
            d = {
                    'comment': comment,
                    'comment_form': CommentForm(),
                    'note': note,
                    'reply_form': ReplyForm(),
                    'static': settings.STATIC_URL,
            }
            comment_form = loader.get_template('comments/comment_form.html')
            comment_temp = loader.get_template('comments/comment.html')
            context = RequestContext(request, add_csrf(request, d))
            data = {
                        'comment': comment_temp.render(context),
                        'comment_count': note.comment_count(),
                        'comment_form': comment_form.render(context),
                        'comment_pk': comment.pk,
                        'note_pk': note.pk,
            }
            return HttpResponse(json.dumps(data), mimetype='application/json')
    return HttpResponseRedirect(reverse('readings.views.detail', 
        args=[reading.slug]))
예제 #42
0
def post_comment(request, post_pk):
    # 先获取评论的文章,后面把评论和被评论的文章关联起来
    # 使用Django提供的get_object_404
    # 这个函数的作用是当文章存在是获取 不存在时返回404给用户
    post = get_object_or_404(Post, pk=post_pk)
    # HTTP 请求有get和post 两种 一般用户是通过表单提交数据都是post请求
    # 因此只有当客户的请求是post的时候才需要处理
    if request.method == 'POST':
        # 用户提交的数据存在request.POST中 这是一个字典对象
        # 我们利用这些数据构造了commentform的实例这样的话Django的表单就成了
        # 当调用form_is_vaild()方法时,Django会自动的帮我们检查表单的数据是否符合格式的需求
        form = CommentForm(request.POST)
        if form.is_valid():
            # 检查是否是合法的 调用表单的save()方法保存到数据库
            # commit = False 的作用是仅仅利用,表单的数据生成comment实例,但不保存到评论数据到数据库
            comment = form.save(commit=False)
            # 将评论和被评论的文章连接起来
            comment.post = post
            # 将最终的评论数保存到数据库,调用模型实例的save()方法
            comment.save()
            # 从新定向到 详情页
            return redirect(post)
        else:
            comment_list = post.comment_set.all()
            context = {
                "post": post,
                "form": form,
                "comment_list": comment_list,
            }
            return render(request, "blog/detail.html", context=context)
    return redirect(post)
예제 #43
0
def post_comment(request, post_pk):
    # 这个函数的作用是当获取的文章(Post)存在时,则获取;否则返回 404 页面给用户。
    post = get_object_or_404(Post, pk=post_pk)

    if request.method == 'POST':
        # 用户提交的数据存在 request.POST 中,这是一个类字典对象。
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            # 将评论和被评论的文章关联起来
            comment.post = post
            comment.save()
            # 重定向到 post 的详情页,实际上当 redirect 函数接收一个模型的实例时,它会调用这个模型实例的 get_absolute_url 方法,
            # 然后重定向到 get_absolute_url 方法返回的 URL。
            return redirect(post)
        else:
            # 检查到数据不合法,重新渲染详情页,并且渲染表单的错误。
            # 因此我们传了三个模板变量给 detail.html,
            # 一个是文章(Post),一个是评论列表,一个是表单 form
            # 注意这里我们用到了 post.comment_set.all() 方法,
            # 这个用法有点类似于 Post.objects.all()
            # 其作用是获取这篇 post下的的全部评论,
            # 因为 Post 和 Comment 是 ForeignKey 关联的,
            # 因此使用 post.comment_set.all() 反向查询全部评论。
            comment_list = post.comment_set.all()
            context = {'post': post,
                       'form': form,
                       'comment_list': comment_list
                        }
            return render(request, 'blog/detail.html', context=context)
    # 不是 post 请求,说明用户没有提交数据,重定向到文章详情页。
    return redirect(post)
예제 #44
0
파일: views.py 프로젝트: ihfazhillah/blog
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)

    similiar_posts = post.get_similiar_posts()

    comments = post.comments.filter(active=True)

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

        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        form = CommentForm()

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

    return render(request, 'blog/post/detail.html', context)
예제 #45
0
파일: views.py 프로젝트: roysdev/breakup
def post_detail(request, pk=None):
    post = get_object_or_404(Post, pk=pk)
    comment_form = CommentForm()
    is_liked = False
    if post.likes.filter(id=request.user.id).exists():
        is_liked = True
    if request.user.is_authenticated:
        if request.method == 'POST':
            # A comment was posted
            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.user = request.user
                new_comment.post = post
                # Save the comment to the database
                new_comment.save()

    context = {
        'post': post,
        'is_liked': is_liked,
        'comment_form': comment_form
    }
    return render(request, 'posts/post_detail.html', context)
예제 #46
0
def album_details(request, pk):
    '''shows the photos, comments, ratings of an album'''
    album = get_object_or_404(Album, pk=pk)
    # if logged in user is not the album publisher then shows 404 page.
    if not request.user == album.user:
        raise Http404
    photos = album.photos.all()
    comments = album.comments.all()

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)

        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            # assigns the Comment to the requested album.
            comment.album = album
            comment.save()

            return redirect('album:album_details', pk=album.pk)

    else:
        comment_form = CommentForm()

    context = {
        'album': album,
        'photos': photos,
        'comment_form': comment_form,
        'comments': comments
    }

    return render(request, "album/album_details.html", context)
예제 #47
0
 def post(self, request, *args, **kwargs):
     form = CommentForm(request.POST)
     comment = form.save(commit=False)
     comment.resource = Resource.objects.filter(
         id=request.POST.get('resource_id')).first()
     comment.author = self.request.user
     comment.save()
     return HttpResponse("success", content_type='text/plain')
예제 #48
0
파일: views.py 프로젝트: DannyCork/demozoo
class EditCommentView(TemplateView):
	@method_decorator(writeable_site_required)
	@method_decorator(login_required)
	def dispatch(self, request, *args, **kwargs):
		commentable_id = self.args[0]
		comment_id = self.args[1]

		commentable_type = ContentType.objects.get_for_model(self.commentable_model)
		self.commentable = get_object_or_404(self.commentable_model, id=commentable_id)
		self.comment = get_object_or_404(Comment,
			id=comment_id, content_type=commentable_type, object_id=commentable_id)

		if not request.user.is_staff:
			return redirect(self.comment.get_absolute_url())

		return super(EditCommentView, self).dispatch(request, *args, **kwargs)

	def get(self, request, *args, **kwargs):
		self.form = CommentForm(instance=self.comment, prefix='comment')
		context = self.get_context_data()
		return self.render_to_response(context)

	def post(self, request, *args, **kwargs):
		self.form = CommentForm(request.POST, instance=self.comment, prefix='comment')
		if self.form.is_valid():
			self.form.save()
			return redirect(self.comment.get_absolute_url())
		else:
			context = self.get_context_data()
			return self.render_to_response(context)

	def get_context_data(self, **kwargs):
		context = super(EditCommentView, self).get_context_data(**kwargs)
		context['commentable'] = self.commentable
		context['commentable_name'] = self.get_commentable_name(self.commentable)
		context['comment'] = self.comment
		context['comment_form'] = self.form
		context['submit_action'] = self.submit_action
		return context

	template_name = 'comments/edit_comment.html'
예제 #49
0
파일: views.py 프로젝트: ershadul/mysite
def details(request, post_id):
    message = ''
    try:
        post = Post.objects.get(pk=post_id)
        
        if request.method == 'POST':
            data = request.POST.copy()
            form = CommentForm(data)
            if form.is_valid():
                # save
                form.save()
                return HttpResponseRedirect('/posts/index')
            else:
                errors = form.errors
        else:
            form = CommentForm()
            data = {}
                
    except Post.DoesNotExist, e:
        message = str(e)
        post = None
예제 #50
0
파일: views.py 프로젝트: mrigor/blogly
def comment_reply(request, type, parent_id):
    parent_comment = Comment.objects.get(id=parent_id)
    response = {}
    if not parent_comment:
        response['error'] = 'Parent comment not found'
    if request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = CommentForm(request.POST).save(commit=False)
            comment.thread_id, comment.reverse_thread_id = \
                    get_thread_id(type, parent_comment.thing_id, parent_comment)
            comment.author = request.user
            comment.thing_id = parent_comment.thing_id
            comment.type = type
            comment.parent_id = parent_comment.id
            comment.save()
            response['content'] = Markup.unescape(
                Markup(
                    render_to_string(request, 'comments/comment.html', {'comment': comment})
                )
            )

    return render_to_remote_response(request, json_context=response)
예제 #51
0
def comment_submit(request, post_slug):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            post = Post.objects.get(slug=post_slug)
            comment.post = post
            comment.save()

            comment_url = request.GET.get('next', '/')# +"#id-"+str(comment.id)
            return HttpResponseRedirect(comment_url)
        else:
            comment_url = request.GET.get('next', '/')
            return HttpResponseRedirect(comment_url)            
예제 #52
0
def reply_submit(request, comment_id):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.parent = Comment.objects.get(id=comment_id)
            comment.post = comment.parent.post
            comment.save()


            comment_url = request.GET.get('next', '/')+"#id-"+str(comment.id)
            return HttpResponseRedirect(comment_url)
        else:
            comment_url = request.GET.get('next', '/')
            return HttpResponseRedirect(comment_url)            
예제 #53
0
파일: views.py 프로젝트: Hoot215/fictionhub
def comment_submit(request, comment_id):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.parent = Comment.objects.get(id=comment_id)
            comment.post = comment.parent.post
            comment.save()
            comment_url = request.GET.get('next', '/')+"#id-"+str(comment.id)
            return HttpResponseRedirect(comment_url)
        else:
            # return HttpResponse("string")
            return render(request, 'posts/create.html', {
                'form':form,
            })
예제 #54
0
def post_comment(request):
    """
    Handles comment submissions
    """
    form = CommentForm(request.POST, auto_id="%s", prefix="CommentForm")

    if form.is_valid():
        comment = form.save(commit=False)
        comment.ip_address = request.META.get("REMOTE_ADDR", None)

        comment.save()

        if request.is_ajax():
            response = simple.direct_to_template(request, "comments/form.json", {
                "comment": comment,
                "total": Comment.objects.get_for_model(comment.obj).count(),
            }, mimetype="application/json")
        else:
            response = HttpResponseRedirect(comment.get_absolute_url())

        if form.cleaned_data.get("remember", False):
            response.set_cookie("comment_author", value=comment.author)
            response.set_cookie("comment_email", value=comment.email)
        else:
            response.delete_cookie("comment_author")
            response.delete_cookie("comment_email")

        return response
    else:
        if request.is_ajax():
            if form.errors:
                errors = simplejson.dumps(form.errors, cls=LazyEncoder, ensure_ascii=False)
            else:
                errors = None

            template = "comments/form.json"
            mimetype = "application/json"
        else:
            errors = None
            template = "comments/form.html"
            mimetype = None

        return simple.direct_to_template(request, template, {
            "form": form,
            "errors": errors,
            "total": 0,
        }, mimetype=mimetype)
예제 #55
0
def submit(request):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.posted_by = request.user
            comment.save()
            return HttpResponseRedirect("%s#%s" % (
                comment.link.get_absolute_url(), comment.id))
        else:
            print form.errors
    link_id = request.POST.get("link", False)
    if link_id:
        link = Link.objects.get(id=link_id)
        return HttpResponseRedirect(link.get_absolute_url())
    #----------
    return HttpResponseRedirect("/")
예제 #56
0
def save_comment(request):
    form = CommentForm(request.POST)
    comment = form.save(commit=False)
    comment.ip = request.META.get("REMOTE_ADDR", "")
    comment.created = datetime.today()
    comment.status = 0
    comment.save()

    if request.POST.get("ret"):
        ret = request.POST.get("ret")
    elif request.META.get("HTTP_REFERER"):
        ret = request.META.get("HTTP_REFERER")
    else:
        ret = "/"

    ret += "?err=1"

    return HttpResponseRedirect(ret)
예제 #57
0
def comment_edit(request, comment_id):
    comment = Comment.objects.get(id=comment_id)
    nextpage = request.GET.get("next", "/")

    if request.method == "POST":
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.save()
            return HttpResponseRedirect(nextpage)
    else:
        form = CommentForm(instance=comment)

    return render(request, "comments/comment-edit.html", {"comment": comment, "form": form, "nextpage": nextpage})

    # throw him out if he's not an author
    if request.user != comment.author:
        return HttpResponseRedirect("/")
    return HttpResponseRedirect("/")  # to story list
def comment_new(request):
    if request.method == "POST":
	print("at comment_new")
        form = CommentForm(data=request.POST)
	print(form.errors)
        if form.is_valid():
            comment = form.save(commit=False)
            #comment.post=post
            comment.author = Author.objects.get(user=request.user.id)
            postid = request.POST.get("post_id", "")
            #print("post_id: %s"%postid)
            post = Post.objects.get(post_id=postid)
            #print("post: %s"%post)
            comment.post = post
            comment.pub_date = timezone.now()
            comment.save()
            return redirect('/profile')
    else:
        form = CommentForm()
    return render(request, 'authors/index.html', {'form': form})
예제 #59
0
def add_new_comment(request, solution_id, problem_id):
    solution = Solution.objects.get(pk=solution_id)
    problem = Problem.objects.get(pk=problem_id)
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.content = bleach.clean(comment.content, strip=True)
            comment.user = UserProfile.objects.get(email=request.session['email'])
            comment.save()
            solution.comments.add(comment)
        else:
            raise Http404('Form is not valid')
    problem.description = markdown.markdown(problem.description, extensions=['markdown.extensions.fenced_code'])
    solution = Solution.objects.get(pk=solution_id)
    comments_list = []
    for comment in solution.comments.order_by('-posted'):
        comment.content = markdown.markdown(comment.content, extensions=['markdown.extensions.fenced_code'])
        comments_list.append(comment)
    return HttpResponseRedirect('/problems/'+str(problem_id)+'/show_solution/'+str(solution_id))
예제 #60
0
def comment_submit(request, comment_id):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.parent = Comment.objects.get(id=comment_id)
            comment.post = comment.parent.post
            comment.save()
            # Send Email
            # send_comment_email_notification(comment)
            # if comment.parent.author.email_comments:
            #     commentauthor = comment.author.username
            #     topic = commentauthor + " has replied to your comment"
            #     body = commentauthor + " has replied to your comment\n" +\
            #            "http://fictionhub.io"+comment.post.get_absolute_url()+ "\n" +\
            #            "'" + comment.body[:64] + "...'"
            #     body += "\n\nYou can manage your email notifications in preferences:\n" +\
            #             "http://fictionhub.io/preferences/"
            #     try:
            #         email = comment.parent.author.email
            #         send_mail(topic, body, '*****@*****.**', [email], fail_silently=False)
            #     except:
            #         pass
            # Notification
            message = Message(
                from_user=request.user,
                to_user=comment.parent.author,
                story=comment.post,
                comment=comment,
                message_type="reply",
            )
            message.save()
            comment.parent.author.new_notifications = True
            comment.parent.author.save()

            comment_url = request.GET.get("next", "/") + "#id-" + str(comment.id)
            return HttpResponseRedirect(comment_url)
        else:
            # return HttpResponse("string")
            return render(request, "posts/create.html", {"form": form})