Esempio n. 1
0
def task_comment(request,slug,task_id):
    print request.POST.get('comment')
    print request.FILES.get('file')
    project = Project.objects.get(slug=slug,organization=request.user.organization)
    task = Ticket.objects.get(id=task_id)
    form = CommentForm(request.POST,task=task,user=request.user,file=request.FILES.get('file'),project=project)

    print form.is_valid()
    if form.is_valid():
        comment = form.save()
        print comment
        return HttpResponse(json.dumps({'error':False}), content_type="json/application")
    else:
        return HttpResponse(json.dumps({'error':True,'errors':form.errors}), content_type="json/application")
Esempio n. 2
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user,
                                                  post_id=post_id,
                                                  comment_text=comment_text)
            comment.save()
            comment = CommentModel.objects.filter(
                user=user, post_id=post_id, comment_text=comment_text).first()
            to_email = Email(comment.post.user.email)
            subject = "Insta-clone Community"
            content = Content(
                "text/plain", "Hi " + comment.post.user.username +
                ",\n      " + user.username + " has commented - " +
                comment_text + " on your post.")
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            print(response.status_code)
            print(response.body)
            print(response.headers)
            return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 3
0
def add_comment(request, article_id):
	a = Article.objects.get(id=article_id)
	if request.method == "POST":
		f = CommentForm(request.POST)
		if f.is_valid():
			c = f.save(commit=False)
			c.pub_date = timezone.now()
			c.article = a
			c.approved = False
			codes = random_code() + format(timezone.now(), u'U')
			c.code = codes
			c.save()

			message = c.name + " commented on your article: " + c.article.title + "<br><br>" + c.body
			message = message + "<br><br><br><br>Follow this link to approve<br><a href='http://127.0.0.1:8000/articles/approvecom/" + codes + "/'>http://127.0.0.1:8000/articles/approvecom/" + codes + "/</a><br><br>"
			message = message + "<br><br>Follow this link to delete<br><a href='http://127.0.0.1:8000/articles/deletecom/" + codes + "/'>http://127.0.0.1:8000/articles/deletecom/" + codes + "/</a>"
			msg = EmailMessage('Comment needs approval', message, '*****@*****.**', ['*****@*****.**'])
			msg.content_subtype = "html"
			msg.send()

			return HttpResponseRedirect('/articles/get/%s' % article_id)

	else:
		f = CommentForm()

	args = {}
	args.update(csrf(request))

	args['article'] = a
	args['form'] = f

	return render_to_response('add_comment.html', args)
Esempio n. 4
0
def show_suggestion(request, suggestion_pk):

    suggestion = get_object_or_404(Suggestion, pk=suggestion_pk)
    comments = suggestion.comments.all()

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

        if comment_form.is_valid():
            instance = comment_form.save(commit=False)
            instance.comment_by = request.user
            instance.suggestion = suggestion
            instance.save()

            return HttpResponseRedirect(reverse('suggestion_detail',
                                                kwargs={'suggestion_pk' : suggestion.pk}))

    else:
        comment_form = CommentForm()

    return render_to_response('sdvapp/suggestion_detail.html',
                              {'suggestion' : suggestion,
                               'comments' : comments,
                               'comment_form' : comment_form,},
                              context_instance=RequestContext(request))
Esempio n. 5
0
def post_project_comment(request, project_author, project_pk):
    user = request.user
    project = get_object_or_404(Project, pk=project_pk)

    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            text = comment_form.cleaned_data["text"]
            comment = Comment(text=text, author=user, project=project)
            comment.save()

            project_notification(
                project,
                user,
                "Clusterify -- new comment on project",
                render_to_string(
                    "projects/emails/comment_on_project.txt",
                    {"project": project, "comment": comment, "site_url": get_full_url()},
                ),
            )

            return HttpResponseRedirect(project.get_absolute_url())
    else:
        comment_form = CommentForm()

    return single_project(request, project_author, project_pk, comment_form)
Esempio n. 6
0
def comments(request):
    comments_list = Comment.objects.order_by('-created_at')

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            captcha_response = request.POST.get['g-recaptcha-response']
            data = {
                'secret': '6LcdyuAUAAAAAGtSgh1HroDq1k6SMMHjX0g8AJ9c',
                'response': captcha_response
            }
            r = requests.post(
                'https://www.google.com/recaptcha/api/siteverify', data=data)
            result = r.json()

            if result['success']:
                form.save()
                messages.success(request, 'New comment added with success!')
            else:
                messages.error(request, 'Invalid reCAPTCHA. Please try again.')

            return redirect('comments')
    else:
        form = CommentForm()

    return render(request, 'comments.html', {
        'form': form,
        'comments': comments_list
    })
Esempio n. 7
0
def comment_view(request):
    user = check_validation(request)
    abuse_msg = ""
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')

            print checkComment(comment_text)
            if checkComment(comment_text) == 1:
                comment = Comment.objects.create(user=user,
                                                 post_id=post_id,
                                                 comment_text=comment_text)
                post = Post.objects.filter(id=post_id).first()
                comment_email(user.username, post.user.email)
                comment.save()
                return redirect('/login_success/')

            else:
                abuse_msg = "Please avoid use of abusive language."
                return render(request, 'login_success.html',
                              {'abuse_msg': abuse_msg})
        else:

            return redirect('/login_success/')
    else:
        return redirect('/login')
Esempio n. 8
0
def comment_view(request):
    # check if user is valid
    user = check_validation(request)
    # check user exists & request is POST
    if user and request.method == "POST":
        form = CommentForm(request.POST)
        # check if form is valid
        if form.is_valid():
            # retrieve post id
            post_id = form.cleaned_data.get('post').id
            # accept the comment-text from the form
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user,
                                                  post_id=post_id,
                                                  comment_text=comment_text)
            # save the comment
            comment.save()
            # redirect to the feeds page
            return redirect('/feed/')
        else:
            # redirect to the feeds page
            return redirect('/feed/')
    else:
        # redirect to the login page
        return redirect('login/')
Esempio n. 9
0
def blog_detail(request, slug):
#    try:
#        log_write(request)
#    except:
#        pass
    user = request.user

    content = get_object_or_404(Blog, slug=slug)
    comments = Comment.objects.filter(blog=content)
    context = {'content': content, 'comments': comments}
    context.update(csrf(request))

    if request.method == 'POST' and user.is_authenticated():
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            ip = request.META['REMOTE_ADDR']
            comment_form.save(content, user, ip)
            return redirect(request.META['HTTP_REFERER'])
    else:
        comment_form = CommentForm()
    context['comment_form'] = comment_form

    Blog.objects.filter(id=content.id).update(
        views_count=F('views_count') + random.randint(1, 3)
    )

    return render(request, 'blog/blog_detail.html', context)
Esempio n. 10
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user,
                                                  post_id=post_id,
                                                  comment_text=comment_text)
            comment.save()
            sg = sendgrid.SendGridAPIClient(apikey=(sendgrid_api_key))
            from_email = Email("*****@*****.**")
            to_email = Email(comment.post.user.email)
            subject = "Comment!"
            content = Content("text/plain", "Your post has a new comment.")
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            print(response.status_code)
            print(response.body)
            print(response.headers)
            return redirect('/Feeds/')
        else:
            return redirect('/Feeds/')
    else:
        return redirect('/Login/')
Esempio n. 11
0
def comment_view(request):
        user = check_validation(request)

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

            if form.is_valid():
                post_id = form.cleaned_data.get('post').id
                comment_text = form.cleaned_data.get('comment_text')
                comment = CommentModel.objects.create(user=user, post_id=post_id, comment_text=comment_text)
                comment.save()
                sg = sendgrid.SendGridAPIClient(apikey=key)
                from_email = Email("*****@*****.**")
                to_email = Email(comment.post.user.email)
                subject = "Knock Knock"
                content = Content("text/plain", "Hey! Someone just commented on your post.")
                mail = Mail(from_email, subject, to_email, content)
                response = sg.client.mail.send.post(request_body=mail.get())
                print(response.status_code)
                print(response.body)
                print(response.headers)

                return redirect('/feed/')

            else:
                return redirect('/feed/')

        else:
            return redirect('/login')
Esempio n. 12
0
def add_comment(request):
    cmt_content = request.POST.get('content', '')
    if not cmt_content.strip():
        return HttpResponse('Write content')

    if request.POST.has_key('entry_id') == False:
        return HttpResponse('Select write')
    else:
        entry = get_object_or_404(WritingEntries, id = request.POST['entry_id'])
    #try:
    form = CommentForm(request.POST)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.user = request.user
        comment.writingEntry = entry
        comment.save()
        entry.comments += 1
        entry.save()
        var = RequestContext(request, {

        })
        return redirect(reverse("board-read", kwargs={"entry_id":request.POST['entry_id']}))
    #except:
        return HttpResponse('There is error')

    return HttpResponse('Error!!')
Esempio n. 13
0
def edit_post(request, pk_thread=None, pk_post=None):
    """Edit a thread."""
    post = get_object_or_404(Post, pk=pk_post)   
    thread = get_object_or_404(Thread, pk=pk_thread)
    forum = Forum.objects.get(thread__pk=pk_thread)

    is_admin = False
    club = Club.objects.get(forum=forum)
    student = StudentProfile.objects.get(user=request.user)
    if Member.objects.filter(club=club, student__user=request.user, admin=True):
        is_admin = True
        
    if pk_post:
        post = get_object_or_404(Post, pk=pk_post)
        if post.creator != request.user and is_admin == False:
            raise Http404
    else:
        post = Post(creator=request.user)
            
    if request.POST:
        form = CommentForm(request.POST, instance=post)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect(reverse("forum.views.thread", args=[pk_thread]) + "?page=last")   
    else:
        form = CommentForm(instance=post)
    
    return render_to_response('forum/post_edit.html', add_csrf(request, form=form), context_instance=RequestContext(request)) 
Esempio n. 14
0
def edit_post(request, model, pk):
    profile = request.user.get_profile()

    if model == "comment":
        post = Comment.objects.get(pk=pk)
        form = CommentForm(instance=post)
    elif model == "post":
        post = Post.objects.get(pk=pk)
        form = PostForm(instance=post)
    elif model == "message":
        post = Message.objects.get(pk=pk)
        form = MessageForm(instance=post)

    if post.author == profile:
        print ""
        if request.POST:
            if model == "comment":
                form = CommentForm(request.POST, instance=post)
            elif model == "post":
                form = PostForm(request.POST, instance=post)
            elif model == "message":
                form = MessageForm(request.POST, instance=post)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect("/")

        return render(
            request, "publication/change_post.html", {"model": model, "form": form, "post": post, "profile": profile}
        )
    else:
        return HttpResponseRedirect("/")
Esempio n. 15
0
def get_post(request, slug):
    event = get_object_or_404(EventModel, slug=slug)
    comm_parent = Comment.objects.filter(is_parent=True).filter(post=event)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            parent_obj = None
            try:
                parent_id = Comment.objects.get(
                    id=int(request.POST.get("parent_id")))
            except:
                parent_id = None
            if parent_id:
                parent_qs = Comment.objects.filter(id=parent_id.id)
                if parent_qs:
                    parent_obj = parent_qs.first()
                    comment.is_parent = False
                else:
                    comment.is_parent = True
            comment.post = event
            comment.user = request.user
            comment.parent = parent_obj
            comment.save()
    return render(request, 'posts/Offer-page.html', {
        'events': event,
        'comm_parent': comm_parent,
        'user': request.user
    })
Esempio n. 16
0
def add_comment(request, id):
    form = CommentForm(request.POST)
    
    if form.is_valid():
        post = Blog.objects.get(id=id)
        form.save(post = post)
        return HttpResponseRedirect('/')
Esempio n. 17
0
def edit_post(request, pk_thread=None, pk_post=None):
    """Edit a thread."""
    post = get_object_or_404(Post, pk=pk_post)
    thread = get_object_or_404(Thread, pk=pk_thread)
    forum = Forum.objects.get(thread__pk=pk_thread)

    is_admin = False
    club = Club.objects.get(forum=forum)
    student = StudentProfile.objects.get(user=request.user)
    if Member.objects.filter(club=club, student__user=request.user,
                             admin=True):
        is_admin = True

    if pk_post:
        post = get_object_or_404(Post, pk=pk_post)
        if post.creator != request.user and is_admin == False:
            raise Http404
    else:
        post = Post(creator=request.user)

    if request.POST:
        form = CommentForm(request.POST, instance=post)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect(
                reverse("forum.views.thread", args=[pk_thread]) + "?page=last")
    else:
        form = CommentForm(instance=post)

    return render_to_response('forum/post_edit.html',
                              add_csrf(request, form=form),
                              context_instance=RequestContext(request))
Esempio n. 18
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user, post_id=post_id, comment_text=comment_text)
            comment.save()
            sg = sendgrid.SendGridAPIClient(apikey=(sendgrid_key))
            from_email = Email("*****@*****.**")
            to_email = Email(comment.post.user.email)
            subject = "Welcome to Swacch Bharat"
            content = Content("text/plain",
                              "Swacch Bharat team welcomes you!\n We hope you like sharing the images of your surroundings to help us build a cleaner india/n")
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            print(response.status_code)
            print(response.body)
            print(response.headers)
            return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 19
0
def create_comment_answer(request, answer_id):
	a = Answer.objects.get(id=answer_id)
	
	if request.POST:
		f = CommentForm(request.POST)
		if f.is_valid():
			c = f.save(commit=False)
			c.pub_date = timezone.now()
			c.related_answer = a
			c.posted_by = request.user
			c.save()
			a.num_comments += 1
			a.comments.add(c)
			a.save()
					
			return HttpResponseRedirect('/get/%s' % a.related_article_id)
	else:
		f = CommentForm()
	
	args = {}
	args.update(csrf(request))
	args['article'] = a
	args['form'] = f
	
	return render(request, 'add_comment.html', args)	
Esempio n. 20
0
def post_view(request, post_id):
    post = get_object_or_404(Post,id=post_id)
    if not post.active:
        return HttpResponseNotFound()
    
    other_posts = Post.objects.filter(tag=post.tag).exclude(id=post.id)[:10]

    captcha = CaptchasDotNet(client = 'barauskas',secret   = 'K1Qurc2oCY09sJA63cpseGEz3zOpwzDeZeR6YNvf')
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            if captcha.verify(form.cleaned_data['captcha'],request.session.get('rand','')):
                form.instance.post = post
                comment = form.save()
                #comment.post = post
                #comment.save()
                form = CommentForm(initial={'author':get_user_name()})
            else:
                form.errors['captcha']=['Captcha is unvalid!']
    else:
        form = CommentForm(initial={'author':get_user_name()})
    rand = str(int(random()*1000000))
    request.session['rand']=rand
    return render_to_response('blog/view.html',
                              {'post': post,
                               'other_posts': other_posts,
                               'form': form,
                               'captcha':captcha.image_url(rand)
                               },
                              context_instance=RequestContext(request))    
Esempio n. 21
0
def comment(request):
    if request.is_ajax():
            form = CommentForm(request.POST)

            if form.is_valid():
                blog_id = request.GET.get('blog_id')
                blog = get_object_or_404(Blog, pk=blog_id)
                blog.comment_num += 1
                blog.save()
                # pre_comid = form.cleaned_data['pre_comid']
                nickname = form.cleaned_data['anickname']
                email = form.cleaned_data['bemail']
                website = form.cleaned_data['cwebsite']
                content = form.cleaned_data['dcontent']
                photo = str(random.randint(0, 9)) + '.png'
                u = User(name=nickname, email=email, website=website, photo=photo)
                u.save()
                c = Comment(user=u, blog=blog, content=content, comment_time=timezone.now())
                c.save()
                # sendCommentReply(email)
                # SendEmail_Comment(nickname,None)
                return ResponseMsg(True, u'谢谢你的评论')
            else:
               return ResponseMsg(False, form.errors.popitem()[1])
    else:
        raise Http404
Esempio n. 22
0
def add_comment(request, article_id):
    a = Article.objects.get(id=article_id)

    if request.method == "POST":
        f = CommentForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.pub_date = timezone.now()
            c.article = a
            c.save()

            messages.success(request, "You Comment was added")

            return HttpResponseRedirect("/articles/get/%s" % article_id)

    else:
        f = CommentForm()

    args = {}
    args.update(csrf(request))

    args["article"] = a
    args["form"] = f

    return render_to_response("add_comment.html", args)
Esempio n. 23
0
def add_comment(request, book_id):
    book = Book.objects.get(id=book_id)
    if request.POST:
        f = CommentForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.book = book
            c.save()
            return HttpResponseRedirect('/books/book/%s' % books_id)
    else:
        f = CommentForm()

    args = {}
    args.update(csrf(request))
    args['book'] = book
    args['form'] = f

    # right box
    args['menu'] = Menu.objects.all()
    args['pop_books'] = Book.objects.all().order_by('likes').reverse()[:10]
    args['new_books'] = Book.objects.all().order_by('date').reverse()[:10]
    args['cats'] = Category.objects.all()
    args['tags'] = Tag.objects.all()
    args['current_item'] = 'книги'

    # user
    args['username'] = auth.get_user(request).username

    # poll
    args['question_web'] = Question.objects.get(text=u"Как вам наш сайт?")
    args['choices'] = Choice.objects.filter(question_id=args['question_web'].id)
    return render_to_response('book/book.html', args)
Esempio n. 24
0
    def post(self, request, *args, **kwargs):
        user = request.user
        restaurant = Restaurant.objects.get(pk=kwargs['pk'])
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.restaurant = restaurant
            comment.time = datetime.datetime.now()
            comment.buyer =request.user
            comment.save()
            comment_form = CommentForm()

        address = Address.objects.get(restaurant=restaurant)
        dishesObject = Dish.objects.filter(restaurant=restaurant)
        dishes = dishesObject.extra(
            select={'total_like': 'liked/(liked+unliked)'},
            order_by=['-total_like']
        )[:3]
        comment = list(Comment_R.objects.filter(restaurant=restaurant).order_by('-time'))
        ratetotal = Comment_R.objects.filter(restaurant=restaurant)
        ratecount = ratetotal.count()
        temp = 0

        for r in ratetotal:
            temp = temp + r.rating
        if ratecount == 0:
            rate = 0
        else:
            rate = temp / ratecount

        return render(request, self.template,
                      {'NavSearchForm':NavSearchForm, 'restaurant': restaurant, 'address': address, 'dishes': dishes, 'dishcount': dishesObject.count(),
                       'comment': comment, 'comment_form': comment_form, 'rate': round(rate,1), 'ratecount': ratecount})
Esempio n. 25
0
def comments(request):

    form = CommentForm(request.POST or None)

    img_form = ImageUploadForm()
    if request.method == "POST" and form.is_valid():
        comment = Comment(content=form.cleaned_data.get('content'))
        if form.cleaned_data.get('quote_id'):
            comment.quote_id = form.cleaned_data.get('quote_id')

        if request.is_ajax():
            print 'ajax coming~~!'
            print comment.id
            print comment.content
            comment.content += ' (from ajax!)'

        comment.save()
        print 'success!'
        return redirect('/comments/')

    comments = Comment.objects.order_by('-id').all()[:8]
    img_paths = ImagsPath.objects.order_by('-id').all()[:5]
    c = {
        'comments': comments,
        'form': form,
        'img_form': img_form,
        'img_paths': img_paths,
    }

    return render(request, 'comments.html', c)
Esempio n. 26
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = str(form.cleaned_data.get('comment_text'))
            abusive_content = abuse(comment_text)
            print(abusive_content)
            if abusive_content['sentence_type'] == "Abusive":
                error_message = "You are trying to add an inapproprite comment!!"
                return render(
                    request, 'error.html', {'error_message': error_message}
                )  # redirecting to page displaying error if user tries to post an inapproprite comment
            else:

                comment = CommentModel.objects.create(
                    user=user, post_id=post_id, comment_text=comment_text)
                comment.save()
                post = PostModel.objects.get(id=post_id)
                recipient_mail = post.user.email
                recipient_name = comment.user.username
                sending_mail(recipient_mail,
                             content_text=recipient_name +
                             " has commented on your post")
                return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login/')
Esempio n. 27
0
def article(request, post_id, post_name):
    post = Post.posts.get_visible_post(post_id)

    if not post:
        raise Http404

    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = Comment()
            comment.author = comment_form.cleaned_data['author']
            comment.post = post
            comment.email = comment_form.cleaned_data['email']
            comment.text = comment_form.cleaned_data['text']
            comment.save()
            return HttpResponseRedirect("/")
        else:
            # TODO SHOW ERRORS
            pass

    spotlighted = Project.objects.filter(related_posts=post)
    comments = Comment.objects.filter(post=post)
    related = TaggedItem.objects.get_related(post, Post)[:6]
    comment_form = CommentForm()

    return render_to_response('article.html',
            {
                "post": post,
                "comments": comments,
                "related": related,
                "spotlighted": spotlighted,
                "comment_form": comment_form
            },
            context_instance=RequestContext(request))
Esempio n. 28
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            post = PostModel.objects.filter(pk=post_id)
            comment_text = str(form.cleaned_data.get('comment_text'))
            set_api_key('0qqGfin1x8jlBmHYYft245Shx9YZdoZq8bi83ZlUYDs')
            review = sentiment(comment_text)
            print review

            if review['sentiment']:
                comment = CommentModel.objects.create(user=user, post_id=post_id, comment_text=comment_text,
                                                      review=review['sentiment'])
                print comment.review
                comment.save()
                return redirect('/feed/')

            else:
                redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 29
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user,
                                                  post_id=post_id,
                                                  comment_text=comment_text)
            comment.save()
            sg = sendgrid.SendGridAPIClient(apikey=(SENDGRID_API_KEY))
            from_email = Email("*****@*****.**")
            to_email = Email(comment.post.user.email)
            subject = "Welcome to Smartblog"
            content = Content(
                "text/plain",
                "Team Smartblog welcomes you!\n We hope you enjoy sharing your precious moments blogging them /n"
            )
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            print(response.status_code)
            print(response.body)
            print(response.headers)
            return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 30
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user, post_id=post_id, comment_text=comment_text)
            comment.save()
            post = form.cleaned_data.get('post')
            email = post.user.email
            #print email

            # sending email to user who created the post about the comment
            sg = sendgrid.SendGridAPIClient(apikey=apikey)
            from_email = Email(my_email)
            to_email = Email(email)
            subject = "Swacch Bharat-new comment"
            content = Content("text/plain", "you have a new comment :" + comment_text)
            mail = Mail(from_email, subject, to_email, content)
            sg.client.mail.send.post(request_body=mail.get())

            return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 31
0
def create_comment_answer(request, answer_id):
    a = Answer.objects.get(id=answer_id)

    if request.POST:
        f = CommentForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.pub_date = timezone.now()
            c.related_answer = a
            c.posted_by = request.user
            c.save()
            a.num_comments += 1
            a.comments.add(c)
            a.save()

            return HttpResponseRedirect('/get/%s' % a.related_article_id)
    else:
        f = CommentForm()

    args = {}
    args.update(csrf(request))
    args['article'] = a
    args['form'] = f

    return render(request, 'add_comment.html', args)
def home(request):
    blog_posts = load_blog()
    results = []
    archieves = []
    for blog in blog_posts:
       body = blog.body
       new_list = [m.start() for m in re.finditer(r"<br />",body)]
       new_line = body.index('<br />')
       for item in new_list:
               if item >= 750:
                  new_line = item
                  break;
       body = body[:new_line]
       pre_start_list = [m.start() for m in re.finditer(r"<pre ",body)]
       pre_end_list = [m.start() for m in re.finditer(r"</pre>",body)]
       if pre_start_list:
            if not pre_end_list:
              pre_end = [m.start() for m in re.finditer(r"</pre>",blog.body)][0]
              body =  blog.body[:pre_end]
       archieves.append(blog.title)
       date = blog.day[:10]
       day = date[8:10]
       month = date[5:7]
       mnth = get_month(month)
       results.append({'day': day, 'month': mnth, 'body': body, 'title': blog.title})
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
           data = form.cleaned_data
           p = Comments(name=data['name'], comment=data['comment'], title=request.POST['post_title'])
           p.save()
    comments = Comments.objects.order_by("-id")
    return render(request, 'home.html', {'posts': results, 'outline': archieves,  'comments': comments, 'form':CommentForm})
Esempio n. 33
0
def blog_detail(request, slug):
    user = request.user
    
    SLUGS = [
        'slug',
        'drupal_slug',
        'nid',
        'id',
    ]

    for slug_name in SLUGS:
        try:
            if 'id' not in slug_name or slug.isdigit():
                content = Blog.objects.get(**{slug_name: slug})
                break
        except Blog.DoesNotExist:
            continue
    else:
        raise Http404
       
    comments = Comment.objects.filter(blog=content).order_by('-create_time')
    contents = {'content': content, 'comments': comments}
    contents.update(csrf(request))

    if request.method == 'POST' and user.is_authenticated():
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            ip = request.META['REMOTE_ADDR']
            comment_form.save(content, user, ip)
            return redirect(request.META['HTTP_REFERER'])
    else:
        comment_form = CommentForm()
    contents['comment_form'] = comment_form

    return render(request, 'blog/blog_detail.html', contents)
Esempio n. 34
0
def add(request):
    user = request.user
    if request.method == 'GET':
        initial = {}
        if user.is_authenticated():
            try:
                profile = request.user.get_profile()
            except:
                profile = None
            initial['username'] = '******'.join([
                name for name in user.last_name, user.first_name,
                getattr(profile, 'middle_name', '') if name
            ])
            if not initial['username']:
                initial['username'] = request.user.username
            initial['email'] = request.user.email
        initial['base_object'] = request.GET.get('bid')
        initial['re'] = request.GET.get('re')
        form = CommentForm(initial=initial)
    else:
        data = dict([(key, value.strip())
                     for key, value in request.POST.items()])
        form = CommentForm(data)
        if form.is_valid():
            comment = form.save()
            if user.is_authenticated():
                comment.author = user
                comment.save()
            return u"Спасибо за Ваш комментарий! После рассмотрения модератором он будет опубликован!<p><a href=''>Обновить страницу</a></p>"
    context = {'form': form}
    return template_loader.get_template("tsogu_comments_form.html").render(
        RequestContext(request, context))
Esempio n. 35
0
def comment(request, id):
    print("enter!!!")
    context = {}
    print(Post.objects.all())
    print("comment!!")
    post = get_object_or_404(Post, id=id)
    if (not post):

        context['error'] = 'The post does not exist.'
        return render(request,
                      'grumblr/comments.json',
                      context,
                      content_type='application/json')

    new_comment = Comment.objects.create(author_user_profile=get_object_or_404(
        UserProfile, user=request.user),
                                         time=datetime.datetime.now(),
                                         post=post)
    comment_form = CommentForm(request.POST, instance=new_comment)
    if not comment_form.is_valid():
        context['error'] = 'The comment is invalid.'
        return render(request,
                      'grumblr/comments.json',
                      context,
                      content_type='application/json')
    new_comment = comment_form.save()
    context['comment'] = new_comment
    return render(request, 'grumblr/comment.html', context)
Esempio n. 36
0
def add_comment(request, article_id):

    print article_id
    a = Article.objects.get(id=article_id)

    values = {}
    values.update(csrf(request))

    values['form'] = CommentForm()
    values['article'] = a

    page = render_to_response("add_comment.html", values)
    print "Checking whether a form was submitted"
    print request.method
    if request.method == 'POST':
        print "Form submitted"
        f = CommentForm(request.POST)
        if f.is_valid():
            print "Form is valid"
            c = f.save(commit=False)

            c.pub_date = timezone.now()
            c.article = a
            c.save()
            page = HttpResponseRedirect('/articles/get/%s' % article_id)

    return page
Esempio n. 37
0
def add_comment(request, article_id):
    a = Article.objects.get(id=article_id)

    if request.method == "POST":
        f = CommentForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.pub_date = timezone.now()
            c.article = a
            c.save()

            messages.success(request, "You Comment was added")

            return HttpResponseRedirect('/articles/get/%s' % article_id)

    else:
        f = CommentForm()

    args = {}
    args.update(csrf(request))

    args['article'] = a
    args['form'] = f

    return render_to_response('add_comment.html', args)
Esempio n. 38
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post = form.cleaned_data.get('post')
            email = post.user.email
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user,
                                                  post=post,
                                                  comment_text=comment_text)
            comment.save()

            sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api)
            from_email = Email("*****@*****.**")
            to_email = Email(email)
            subject = "Upload to win"
            content = Content("text/plain",
                              user.name + " has commented on your post")
            mail = Mail(from_email, subject, to_email, content)
            sg.client.mail.send.post(request_body=mail.get())
            return redirect('/feed/')

        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 39
0
def add_comment(request, article_id):
    a = Article.objects.get(id=article_id)

    if request.method == "POST":
        f = CommentForm(request.POST)
        if f.is_valid():
            # save this frm but do NOT push anything into db
            c = f.save(commit=False)
            c.pub_date = timezone.now()
            # RELATIONSHIP: relate this COMMENT with correcponding ARTICLE
            c.article = a
            c.save()

            return HttpResponseRedirect('/articles/get/%s' % article_id)

    # if this is not the POST method - so the first time we are seeing this
    else:
        f = CommentForm()

    args = {}
    args.update(csrf(request))

    args['article'] = a
    args['form'] = f

    return render_to_response('add_comment.html', args)
Esempio n. 40
0
def show_issue(request, related_issue, user_status='group_task_receiver'):
    # use "filter" to exclude all deleted issues without extra "if"
    issue = Issue.objects.filter(pk=related_issue).exclude(status = 'deleted')[0]
    if request.method == 'POST' and 'comment' in request.POST:
        form = CommentForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            comment = Comment()
            comment.add(cd, request.user, issue.id)
        return HttpResponseRedirect("")
    elif request.method == 'POST' and 'comment' not in request.POST:
        status = [key for key in request.POST]
        issue.renew_status(status[0], request.user)
        return HttpResponseRedirect("")
    else:
        issue.count_comments()
        issue.define_condition()
        counter = count_issues(request)
        comments = comments_gettext_loop(Comment.objects.filter(issue=issue).order_by('date'))
        if request.user in issue.receiver.all():
            user_status = 'receiver'
        if request.user == issue.author:
            user_status = 'author'
        form = CommentForm()
    return render_to_response('issue_page.html', {'form': form,
                                                  'user': request.user,
                                                  'issue': issue,
                                                  'comments': comments,
                                                  'user_status': user_status,
                                                  'receivers': issue.receiver.all(),
                                                  'counter': counter,
    })
Esempio n. 41
0
def idea(request, offset):
    try:
        offset = int(offset)
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
                comment_info = form.cleaned_data
                comment_text_form = comment_info['comment_text']
                comment_agree_form = 1  #placeholder
                idea_id_form = int(offset)
                comment = Comment(comment_text=comment_text_form,
                                  comment_agree=comment_agree_form,
                                  idea_id=idea_id_form)
                comment.save()
                url = '/idea/' + str(offset)
                return HttpResponseRedirect(url)
        else:
            idea = Idea.objects.get(id=offset)
            idea_title = idea.idea_title
            idea_text = idea.idea_text
            #comments = idea.comment_set.all()
            comments = Comment.objects.filter(idea_id=offset).reverse()
            form = CommentForm
    except ValueError:
        raise Http404()
    return render(
        request, 'idea.html', {
            'idea_title': idea_title,
            'idea_text': idea_text,
            'comments': comments,
            'form': form
        })
Esempio n. 42
0
def post_comments(request, year, month, slug):
    context = dict()
    context.update(csrf(request))
    now = datetime.datetime.now()
    if year and month and slug:
        post = Post.objects.get(created__year=int(year), created__month=int(month), slug=slug)

        form = CommentForm(request.POST or None)
        if request.method == 'POST':
            if form.is_valid():
                comment = form.save(commit=False)
                u = User.objects.get(username=request.user.username)
                comment.author = u
                comment.created = now
                comment.post = post
                comment.save()
                form = CommentForm()
                #TODO maybe should got to blog/year/month/slug
                #return HttpResponseRedirect('/blog%s' % post.get_absolute_url())

    comments = Comment.objects.filter(post=post).order_by("-created")

    context['post'] = post
    context['comments'] = comments
    context['form'] = form
    return render(request, 'post_comments.html', context)
Esempio n. 43
0
def add_comment(request, person_id):
	a = Persons.objects.get(id=person_id)
	if request.method == "POST":
		f = CommentForm(request.POST)
		if f.is_valid():
			c = f.save(commit=False)
			c.CreatedOn = timezone.now()
			c.person = a
			c.save()
	
			messages.success(request, "Your comment was added")
			return HttpResponseRedirect('/persons/get/%s' % person_id)
	else:
		f = CommentForm()
	args = {}
	args.update(csrf(request))
	
	args['person'] = a
	args['form'] = f
	
	return render_to_response('add_comment.html', args)

		
	
	message.add_message(request, settings.DELETE_MESSAGE, "Your comment was deleted successfully")
	return HttpResponseRedirect('/persons/get/%s' % person_id)
Esempio n. 44
0
def	coment_sucesso(request, id):
    form = CommentForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        post = Post.objects.get(id=id)

        print form.cleaned_data['comentario']

        comentario = Comentario()
        comentario.post = post
        comentario.email = request.POST['email']
        comentario.nome  = request.POST['nome']
        comentario.comentario = form.cleaned_data['comentario']
        print comentario.id
        comentario.save()
        print comentario.id

        html = Template("""<a href="{% url 'home' %}">Página inicial</a></br>
               <h2>Comentario postado com sucesso no post {{id}}</h2>
        """).render(Context({'id' : id}))
        return HttpResponse(html)
    else:
        post = get_object_or_404(Post, id=id)

        # Formulário já volta preenchido da view
        form = CommentForm(request.POST or None)

        comentarios = Comentario.objects.filter(post=post)

        return render(request, 'detalhePost.html',
        {'post' : post, 'comentarios' : comentarios, 'form' : form})
Esempio n. 45
0
def comment(request, slug):

	post = BlogPost.objects.get(slug=slug)

	if not post.allowcomments:
		raise PermissionDenied('This post does not allow comments.')

	if request.method == 'POST':

		form = CommentForm(request.POST)

		if form.is_valid():

			data = form.cleaned_data

			comment = BlogPostComment()
			comment.blogpost = post
			comment.authorname = data['name']
			comment.authoremail = data['email']
			comment.authorurl = data['url']
			comment.content = data['content']
			comment.approved = not __isCommentSpam(comment)
			comment.save()

			return HttpResponseRedirect(post.get_absolute_url())

		else:
			# TODO: handle this
			assert(False)

	else:
		raise PermissionDenied('Method not supported')
Esempio n. 46
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user,
                                                  post_id=post_id,
                                                  comment_text=comment_text)
            comment.save()
            apikey = 'UXqiW0EEfpWD1oB8AgJXAveneCAQxkIQSGXZwbAioS0'
            request_url = (
                'https://apis.paralleldots.com/sentiment?sentence1=%s&apikey=%s'
            ) % (comment_text, apikey)
            print 'POST request url : %s' % (request_url)
            sentiment = requests.get(request_url, verify=False).json()
            sentiment_value = sentiment['sentiment']
            print sentiment_value
            if sentiment_value < 0.5:
                print 'Negative Comment'
            else:
                print 'Positive Comment'

            print 'commented'
            return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 47
0
def add_comment(request, event_id):
	e = Event.objects.get(id=event_id)

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

		if f.is_valid():
			user_logger.debug('COMMENTED: '+request.user.username+' to '+event_id)
			c = f.save(commit=False)
			c.pub_date = timezone.now()
			c.username = request.user.username
			c.event = e
			c.save()
			return HttpResponseRedirect('/events/get/%s' % event_id)

	else:
		f = CommentForm()

	args = {}
	args.update(csrf(request))

	args['event'] = e
	args['form'] = f

	return render_to_response('listing.html', args, context_instance=RequestContext(request))
Esempio n. 48
0
def service_comments(request, id):
    service = get_object_or_404(Service, id=id)
    if not service.is_active():
        raise Http404

    # check if user is allowed to comment
    if request.user.is_authenticated():
        now = datetime.datetime.now()
        reservations = Reservation.objects.filter(Q(user=request.user, service=service) & (Q(date__lt=now.date()) | Q(date=now.date(), time__lt=now.time()))).order_by('-date', '-time')
        if len(reservations) and not Comment.objects.filter(author=request.user, service=service, created__gt=datetime.datetime.combine(reservations[0].date, reservations[0].time)).exists():
            # handle form
            if request.method == 'POST':
                form = CommentForm(request.POST)
                if form.is_valid():
                    comment = form.save(commit=False)
                    comment.service = service
                    comment.author = request.user
                    comment.save()
                    return HttpResponseRedirect(reverse(service_comments, args=(id,)))
            else:
                form = CommentForm()

    # get all comments
    comments = service.comments.order_by('-created').all()

    return render_to_response('service/comments.html', locals(), context_instance=RequestContext(request))
Esempio n. 49
0
def add_comment(request):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            client = get_object_or_404(Client,
                                       pk=form.cleaned_data['client_id'])
            selection = get_object_or_404(Selection,
                                          pk=form.cleaned_data['selection_id'])
            if form.cleaned_data['text'] != '':
                author = request.user
                comment_text = form.cleaned_data['text']
                comment = Comment(author=author,
                                  text=comment_text,
                                  selection=selection)
                comment.save()
            if form.cleaned_data['rating'] != '':
                Rating.objects.update_or_create(
                    rater=request.user,
                    talent=selection.talent,
                    defaults={'rating': form.cleaned_data['rating']})
                selection.talent.save()

            return HttpResponseRedirect(request.META.get('HTTP_REFERER'), {
                'selection': selection,
                'client': client
            })
    else:
        return Http404("That page does not exist")
Esempio n. 50
0
def article(request, context, article_id):
    context.update(csrf(request))
    context["article"] = Article.objects.get(id=article_id)
    context["commnets"] = Comment.objects.filter(article=article_id)  # article_id)
    if True:  # context['userAuthenticated']:#see frontEnd decorator
        #################################
        # check commment create:
        if "commentButton" in request.POST:  # comment(create) button clicked!
            comment_form = CommentForm(
                request.POST
            )  # if is valid --> save if not we create a new CommentForm with some error for user(like empty field and ...)
            if comment_form.is_valid():
                writer = context["user"]  # see frontEnd decorator
                body = request.POST["body"]
                Comment.objects.create(writer=writer, body=body, article=context["article"])
                # comment = Comment.objects.create(writer=writer,body=body,article=article)
                return HttpResponseRedirect("")  # just for reload the page and cleaning the fields
        else:
            comment_form = CommentForm()  # create a simple CommentForm
            ##################################
    else:
        comment_form = None
    # set template variable:
    context["comment_form"] = comment_form
    return render_to_response("frontEnd/article/article.html", context)
Esempio n. 51
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data.get('comment_text')
            comment = CommentModel.objects.create(user=user,
                                                  post_id=post_id,
                                                  comment_text=comment_text)
            comment.save()

            sg = sendgrid.SendGridAPIClient(apikey=(sendgrid_key))
            from_email = Email("*****@*****.**")
            to_email = Email(comment.post.user.email)
            subject = "Welcome to My App"
            content = Content("has been commented", "commented/n")
            mail = Mail(from_email, subject, to_email, content)
            response = sg.client.mail.send.post(request_body=mail.get())
            print(response.status_code)
            print(response.body)
            print(response.headers)

            return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login')
Esempio n. 52
0
def add_comment(request, article_id):

    print article_id
    a = Article.objects.get(id=article_id)

    values = {}
    values.update(csrf(request))

    values['form'] = CommentForm()
    values['article'] = a

    page = render_to_response("add_comment.html", values)
    print "Checking whether a form was submitted"
    print request.method
    if request.method == 'POST':
        print "Form submitted"
        f = CommentForm(request.POST)
        if f.is_valid():
            print "Form is valid"
            c = f.save(commit=False)

            c.pub_date = timezone.now()
            c.article = a
            c.save()
            page = HttpResponseRedirect('/articles/get/%s' % article_id)

    return page
Esempio n. 53
0
    def post(self, request, slug):
        product = get_object_or_404(Product, slug=slug)
        like = True
        if request.user.is_authenticated():
            like = Likes.objects.filter(user=request.user,
                                        product=product).exists()
        comments = Comment.objects.filter(product=product,
                                          pub_date__range=[
                                              t.now() - t.timedelta(hours=24),
                                              t.now()
                                          ]).values('name', 'comment')
        form = CommentForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request,
                             'Your comment has been added!')
            return redirect(reverse('test_task:product_detail',
                                    args=[product.slug]))
        else:
            messages.error(request, 'Your comment is not added.')

        context = {'product': product,
                   'comments': comments,
                   'form': form,
                   'like': like}
        return render(request, 'test_task/product_detail.html',
                      context)
Esempio n. 54
0
def add(request):
    redirect_to=COMMENT_REDIRECT_TO
    if request.POST:
        form=CommentForm(request.POST)
        if form.is_valid():
            if 'redirect' in form.cleaned_data:
                redirect_to=form.cleaned_data['redirect']
            else:
                redirect_to=COMMENT_REDIRECT_TO

            if not request.user.is_authenticated():
                msg = _("In order to post a comment you should have a friendsnippets account.")
                msg = urlquote_plus(msg)
                if COMMENT_SIGNIN_VIEW:
                    redirect_to=reverse(COMMENT_SIGNIN_VIEW) + "?next=" + redirect_to + "&msg=" + msg
                else:
                    redirect_to='/'
                if not request.user.is_authenticated():
                    return HttpResponseRedirect(redirect_to)   
            
            try:    
                content_type=ContentType.objects.get(id=form.cleaned_data['content_type'])
            except:
                pass
            if content_type:
                params = {
                    'headline':form.cleaned_data['headline'],
                    'comment':form.cleaned_data['comment'],
                    'user':request.user,
                    'content_type':content_type,
                    'object_id':form.cleaned_data['object_id'],
                }
                c = Comment(**params)
                c.save()
    return HttpResponseRedirect(redirect_to)    
Esempio n. 55
0
def comment_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post_id = form.cleaned_data.get('post').id
            comment_text = form.cleaned_data['comment_text']
            comment = CommentModel.objects.create(user=user,
                                                  post_id=post_id,
                                                  comment_text=comment_text)
            text = form.cleaned_data['comment_text']
            if is_abusive(text):
                ctypes.windll.user32.MessageBoxW(
                    0, u"Your caption contain Abusive content", u"Warning", 0)
                return redirect('/feed/')
            else:
                email = comment.post.user.email
                subject = "Comment on your post"
                body = "Someone just commented on your post"
                send_mail(email, subject, body)
                comment.save()
                ctypes.windll.user32.MessageBoxW(
                    0, u"Comment posted successfully", u"SUCCESS", 0)
                return redirect('/feed/')
        else:
            return redirect('/feed/')
    else:
        return redirect('/login/')
Esempio n. 56
0
def post(request):
    output = dict(success=False)
    form = CommentForm(None, request.POST)
    if form.is_valid():
        form.save(request.user)
        output['success'] = True
    else:
        output['errors'] = form.get_errors()
    return HttpResponse(json.dumps(output), "text/javascript")
Esempio n. 57
0
def comment_create(request, pk):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            post = Post.objects.get(id=pk)
            Comment.objects.create(created_by=request.user,
                                   post=post,
                                   **form.cleaned_data)
            return redirect(reverse_lazy("post_detail", kwargs={"pk": pk}))
Esempio n. 58
0
def addcomment(request, article_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_article = Article.objects.get(id=article_id)
            form.save()
            request.session.set_expiry(60)
            request.session['pause'] = True
    return redirect('/articles/get/%s/' % article_id)
Esempio n. 59
0
def add_comment(request, Lot_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_for_lot = Lot.objects.get(id=Lot_id)
            form.save()
            request.session.set_expiry(60)
            request.session['pause'] = True
    return redirect('http://localhost:8181/show/show_details/%s/' % Lot_id)