def show_post(post_id): post = Post.query.get_or_404(post_id) page = request.args.get('page', 1, type=int) per_page = current_app.config['BLOG_COMMENT_PER_PAGE'] pagination = Comment.query.with_parent(post).filter_by(reviewed=True).order_by(Comment.timestamp.desc()).paginate(page, per_page=per_page) comments = pagination.items if current_user.is_authenticated: form = AdminCommentForm() form.author.data = current_user.name form.email.data = current_app.config['BLUELOG_EMAIL'] from_admin = True reviewed = True else: form = CommentForm() from_admin = False reviewed = False if form.validate_on_submit(): author = form.author.data email = form.email.data body = form.body.data comment = Comment( author=author, email=email, body=body, from_admin=from_admin, post=post, reviewed=reviewed ) replied_id = request.args.get('reply') if replied_id: replied_comment = Comment.query.get_or_404(replied_id) comment.replied = replied_comment db.session.add(comment) db.session.commit() flash('Thanks, your comment will be published after reviewed.', 'info') return redirect(url_for('.show_post', post_id=post_id)) return render_template('blog/post.html', post=post, pagination=pagination, comments=comments, form=form)
def post_comment(request,blog_id): blog=get_object_or_404(Blog,id=blog_id) titl=request.POST['title'] content=request.POST['content'] c=Comment(title=titl,pub_date=timezone.now(),parent=blog,content=content,author=User.objects.get(id=1)) c.save() return HttpResponse('Your comment has been posted!')
def comment(request, post_id): if request.method == 'POST': post_obj = Post.objects.get(id=post_id) mail = request.POST.get('mail') username = request.POST.get('username') message = request.POST.get('message') post = request.POST.get('post', post_id) data = { 'mail': mail, 'username': username, 'message': message, 'post': post_id } form = CommentForm(data) if form.is_valid(): comment = Comment(mail=mail, username=username, message=message, post=post_obj) comment.save() request.session['comment_error'] = False request.session['comment_success'] = True else: request.session['comment_success'] = False request.session['comment_error'] = True else: form = CommentForm() return HttpResponseRedirect( reverse('post_details', kwargs={'slug': post_obj.slug}))
def post(post_id): """View function for post page""" # Form object:'Comment' form = CommentForm() # form.validate_on_submit() will be true and return the # data object to form instance from user enter # when the HTTP request is POST # form.validata_on_submit() 方法会隐式的判断该 HTTP 请求是不是 POST, # 若是, 则将请求中提交的表单数据对象传入上述的 form 对象并进行数据检验. if form.validate_on_submit(): new_comment = Comment(name=form.name.data) new_comment.text = form.text.data new_comment.date = datetime.datetime.now() new_comment.post_id = post_id db.session.add(new_comment) db.session.commit() post = db.session.query(Post).get_or_404(post_id) tags = post.tags comments = post.comments.order_by(Comment.date.desc()).all() recent, top_tags = sidebar_data() return render_template('post.html', post=post, tags=tags, comments=comments, recent=recent, top_tags=top_tags, form=form)
def blog_detail(request, pk): post = Post.objects.get(pk=pk) form = forms.CommentForm() # check if a POST request has been received if request.method == "POST": # if it has, then we create a new instance of our form, # populated with the data entered into the form form = forms.CommentForm(request.POST) # if the form is valid, a new instance of Comment is created # u can access the data from the form using # form.cleaned_data, which is a dict if form.is_valid(): # the keys of the dict corresponds to the form fields, so u can # access the author using form.cleaned_data["author"] comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post, ) comment.save() comments = Comment.objects.filter(post=post) context = { "post": post, "comments": comments, "form": form, } return render(request, "blog_detail.html", context)
def form_valid(self, form): post = self.get_object() comment = Comment(content=form.cleaned_data['content'], author=User.objects.get(username='******'), post=post) comment.save() post.comment_set.add(comment) post.save() return super(PostDetail, self).form_valid(form)
def blog_detail(request, slug): post = get_object_or_404( Post, slug=slug) # if post doesn't exist return error404 comments = Comment.objects.filter(post=post) # comment form form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=request.user, body=form.cleaned_data['body'], post=post, ) comment.save() return HttpResponseRedirect( '/' + slug ) # when a comment is sent, user is redirect to the same page but with empyt form context = { 'post': post, 'comments': comments, 'form': form, 'blog': 'active', 'blog_detail': True, } return render(request, 'blog_detail.html', context)
def add_comment_to_post(id, subName, subComment): blogPostObj = BlogPost.objects.get(pk=id) addComment = Comment(name=subName, comment=subComment, blogPost=blogPostObj) addComment.save() return True
def add_comment(request, slug): """Add a new comment.""" p = request.POST post = Post.objects.get(slug=slug) author_ip = get_ip(request) if p.has_key("body") and p["body"]: author = "Anonymous" if p["author"]: author = p["author"] comment = Comment(post=post) cf = CommentForm(p, instance=comment) cf.fields["author"].required = False comment = cf.save(commit=False) comment.author = author comment.author_ip = author_ip comment.save() messages.success( request, "Thank you for submitting a comment. It will appear once reviewed by an administrator." ) else: messages.error(request, "Something went wrong. Please try again later.") return HttpResponseRedirect(post.get_absolute_url())
def comment_entry_request(request, post_id, user_id): """Triggered when a user inserts a comment in an specific entry""" bp = Entry.objects.get(id=post_id) # Form management if request.method == 'POST': # If the form has been submitted... form = SubmitCommentForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass comment = Comment(entry=bp, author=User.objects.get(id=user_id), text=request.POST['message'], date=datetime.datetime.now(), num=Comment.objects.filter( entry=post_id).count() + 1, quote=0) comment.save() return HttpResponseRedirect(reverse("singlepost", args=(post_id,))) else: form = SubmitCommentForm() # An unbound form return HttpResponse( _singleentry_template_gen( request, 'blog/singlepost.html', Entry.objects.get(id=post_id), Comment.objects.filter(entry=post_id), form))
def GET(self,slug=None): try: page_index=int(self.param('page')) except: page_index=1 cq=self.param('cq') cv=self.param('cv') if cq and cv: query=Comment.all().filter(cq+' =',cv).order('-date') else: query=Comment.all().order('-date') comments,pager=Pager(query=query,items_per_page=15).fetch(page_index) self.render2('views/admin/comments.html', { 'current':'comments', 'comments':comments, 'pager':pager, 'cq':cq, 'cv':cv } )
def view_post(pid): page = request.args.get('page', 1, int) post = get_or_404(Post, Post.id == pid) form = UpdatePostForm() comment_form = CommentForm() com = Comment.get_post_comments(pid) if form.validate_on_submit(): if post.user.id != current_user.id: return abort(403) Post.update(content=form.post_content.data).where( Post.id == post.id).execute() flash('Post update', 'success') return redirect(url_for('.view_post', pid=pid)) if request.method == meth[1]: form.post_content.data = post.content all_comment = Comment.get_post_comments(pid) if all_comment: return object_list('home/view_post.html', Comment.get_post_comments(pid), context_variable='comment_list', post=post, form=form, comment_form=comment_form, paginate_by=2, page=page) return render_template('home/view_post.html', comment_form=comment_form, post=post, form=form, comment_list=all_comment)
def comment_entry_request(request, post_id, user_id): """Triggered when a user inserts a comment in an specific entry""" bp = Entry.objects.get(id=post_id) # Form management if request.method == 'POST': # If the form has been submitted... form = SubmitCommentForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass comment = Comment( entry=bp, author=User.objects.get(id=user_id), text=request.POST['message'], date=datetime.datetime.now(), num=Comment.objects.filter(entry=post_id).count() + 1, quote=0) comment.save() return HttpResponseRedirect(reverse("singlepost", args=(post_id, ))) else: form = SubmitCommentForm() # An unbound form return HttpResponse( _singleentry_template_gen(request, 'blog/singlepost.html', Entry.objects.get(id=post_id), Comment.objects.filter(entry=post_id), form))
def blog_detail(request, pk): # Retrieval of post objects post = Post.objects.get(pk=pk) #Instantiation of form object form = CommentForm() # Checking if it's a post request if request.method == 'POST': form = CommentForm(request.POST) # testing for form validity if form.is_valid(): comment = Comment( # Accessing of form data after validity check author=form.cleaned_data['author'], body=form.cleaned_data['body'], post=post) # Save post comment comment.save() # Filter object based on post during retrieval comments = Comment.objects.filter(post=post) # Context for rendering in template context = { 'post': post, 'comments': comments, 'form': form, } return render(request, 'blog_detail.html', context)
def post(self, request, *args, **kwargs): new_comment = Comment(content=request.POST.get('content'), author=self.request.user, post_connected=self.get_object()) new_comment.save() return self.get(self, request, *args, **kwargs)
def add_comment(request): name = request.POST.get('name', '') if not name.strip(): return HttpResponse('name error') password = request.POST.get('password', '') if not password.strip(): return HttpResponse('password error') password = hashlib.md5(password.encode('utf-8')).hexdigest() website = request.POST.get('website', '') if not website.strip(): return HttpResponse('website error') if website.find("http://") == -1 or website.find("https://") == -1: website = "http://" + website content = request.POST.get('content', '') if not content.strip(): return HttpResponse('content error') post_id = request.POST.get('post_id', '') if not post_id.strip(): return HttpResponse('post_id error') post = Post.objects.get(id=post_id) print('blog.views.add_comment post_id{0}'.format(post_id), sys.stderr) new_cmt = Comment(name=name, password=password, website=website, content=content, post=post) new_cmt.save() return redirect('blog.views.main', slug=post.slug)
def create_comment(request): """ Create comment via Ajax""" # check if the call is ajax if request.is_ajax(): # get post values article_id = request.POST.get('article_id', 0) comment_text = request.POST.get('comment_text', '') # if the comment has any value if comment_text.strip(): # create and save the comment article_obj = get_object_or_404(Article, id=article_id) client = get_object_or_404(Client, user=request.user) comment = Comment(client=client, article=article_obj, text=comment_text) comment.save() return JsonResponse({ 'comment_text': comment.text, 'comment_username': comment.client.user.username, 'comment_date': comment.pub_date }) return HttpResponse('')
def blog_detail(request, pk): # here we get the posts having a specific primary key post = Post.objects.get(pk=pk) # here we create a new instance of the CommentForm class form = CommentForm() # suppose that we have posted the form then we retrieve the data if request.method == 'POST': form = CommentForm(request.POST) # suppose that the form has non empty entries if form.is_valid(): # then you create a new model instance comment = Comment(author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post) comment.save() # now you retrieve the new list of comments after having saved # the previous list of comments comments = Comment.objects.filter(post=post) # you create a new context using the variables you have previously # just defined context = { "post": post, "comments": comments, "form": form, } # then you can reder the html page using the given context which is # used as far as I see ot pass variables to the view return render(request, "post_detail.html", context)
def reply_comment(request): data = request.POST.copy() ctype = data.get("content_type") object_pk = data.get("object_pk") path=data.get('path') user=request.user try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.get(pk=object_pk) except (TypeError,AttributeError,ObjectDoesNotExist): logging.info('object not exits') comment = Comment(content_type = ContentType.objects.get_for_model(target), object_pk = force_unicode(target._get_pk_val()), author=user.username, email=user.email, weburl=user.get_profile().website, content=data.get('comment'), date = datetime.now(), mail_notify=True, is_public = True, parent_id = data.get('parent_id'), ) comment.save() signals.comment_was_submit.send( sender = comment.__class__, comment = comment ) return HttpResponseRedirect(path)
def post_comment(request, entry_id): comment = Comment(entry_id = entry_id, name = request.POST['name'], comment = request.POST['comment'], date = datetime.now()) comment.save(); return entry(request, entry_id)
def comment(request, post_id): if request.method == 'POST': post_obj = Post.objects.get(id = post_id) mail = request.POST.get('mail') username = request.POST.get('username') message = request.POST.get('message') post = request.POST.get('post', post_id) data = { 'mail' : mail, 'username' : username, 'message' : message, 'post' : post_id } form = CommentForm(data) if form.is_valid(): comment = Comment(mail= mail, username=username, message=message, post=post_obj) comment.save() request.session['comment_error'] = False request.session['comment_success'] = True else: request.session['comment_success'] = False request.session['comment_error'] = True else: form = CommentForm() return HttpResponseRedirect(reverse('post_details', kwargs={'slug': post_obj.slug}))
def blog_detail(request, pk): try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: post = None if post: dellink = '' editlink = '' print(type(post.title)) if (str(request.user) == str(post.writer)): dellink = 'Delete' editlink = 'Edit' form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment(author=request.user, body=form.cleaned_data["body"], post=post) comment.save() comments = Comment.objects.filter(post=post).order_by('-created_on') context = { 'dellink': dellink, 'editlink': editlink, "post": post, "comments": comments, "form": form, 'user': request.user, } return render(request, "blog_detail.html", context) else: return HttpResponseRedirect(reverse('blog_index'))
def setUp(self): self.new_user = User(firstname='wahala', password='******') self.new_comment = Comment(id=12345, post_id='2', user_id='2', post_comment='what food do you eat food?', user=self.new_user)
def show_post(post_id): categories = Category.query.all() post = Post.query.get_or_404(post_id) page = request.args.get('page', 1, type=int) per_page = 10 pagination = Comment.query.with_parent(post).order_by( Comment.timestamp.asc()).paginate(page, per_page) comments = pagination.items # if current_user.is_authenticated: # form = AdminCommentForm() # form.author.data = current_user.name # # form.email.data = current_app.config['BLUELOG_EMAIL'] # form.site.data = url_for('.index') # from_admin = True # else: form = CommentForm() if form.validate_on_submit(): body = form.body.data comment = Comment(author=current_user, body=body, post=post) replied_id = request.args.get('reply') if replied_id: replied_comment = Comment.query.get_or_404(replied_id) comment.replied = replied_comment db.session.add(comment) db.session.commit() flash('Comment published.', 'success') return redirect(url_for('.show_post', post_id=post_id)) return render_template('main/post.html', post=post, pagination=pagination, form=form, comments=comments, categories=categories)
def blog_detail(request, pk): """ Show an individual blog article Args: request ([type]): [description] pk ([type]): [description] Returns: [type]: [description] """ post = Post.objects.get(pk=pk) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment(author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post) comment.save() comments = Comment.objects.filter(post=post) context = { "post": post, "comments": comments, "form": form, } return render(request, "blog_detail.html", context)
class CommentsTest(unittest.TestCase): def setUp(self): self.new_blog = Blog(id=40, title='New Blog', content='This is the content', category='Travel', posted=datetime.now()) self.new_comment = Comment(name='Test Comment', comment='This is my Test comment', blog=new_blog) def tearDown(self): db.session.delete(self.new_blog) db.session.commit() db.session.delete(self.new_comment) db.session.commit() def test_instance(self): self.assertTrue(isinstance(self.new_comment, Comment)) def test_save_comment(self): self.new_comment.save_comment() self.assertTrue(len(Comment.query.all()) > 0) def test_check_instance_variables(self): self.assertEquals(self.new_comment.name, 'Test Comment') self.assertEquals(self.new_comment.comment, 'This is my Test comment') self.assertEquals(self.new_comment.blog, new_blog)
class TestComment(unittest.TestCase): def setUp(self): self.new_user = User(firstname='wahala', password='******') self.new_comment = Comment(id=12345, post_id='2', user_id='2', post_comment='what food do you eat food?', user=self.new_user) def tearDown(self): Comment.query.delete() User.query.delete() def test_instance(self): self.assertTrue(isinstance(self.new_comment, Comment)) def test_check_instance_variables(self): self.assertEquals(self.new_comment.id, 12345) self.assertEquals(self.new_comment.blog_id, '2') self.assertEquals(self.new_comment.user_id, '2') self.assertEquals(self.new_comment.post_comment, 'wakanda') self.assertEquals(self.new_comment.user, self.new_user, self.new_post) def test_save_comment(self): self.new_comment.save_comment() comments = Comment.query.all() self.assertTrue(len(comments) > 0)
def blog_detail(request, pk): post = Post.objects.get(pk=pk) # get post based on primary key (pk) # @6.4 form = CommentForm() # create instance of our form class. if request.method == 'POST': # has a POST request been received? form = CommentForm( request.POST ) # If yes, create a new instance of our form with the request populated with the data. if form.is_valid(): # Check to see if form is valid. comment = Comment( # Create new instance of comment. author=form.cleaned_data[ 'author'], # form.cleaned_data represents a dictionary, with keys such as author, body etc. body=form.cleaned_data['body'], post=post # don't forget to add current post to the comment. ) comment.save() # save the comment. comments = Comment.objects.filter( post=post) # retrieve comments for the specific post using filter context = { 'post': post, 'comments': comments, 'form': form, # add form to context dictionary so we can access the form in HTML template. } return render(request, "blog_detail.html", context)
def get_post(request, slug): post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post) if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): parent_id = request.POST.get('parent') text = request.POST.get('text') if parent_id: parent = get_object_or_404(Comment, id=int(parent_id)) comment = Comment(post=post, text=text, author=request.user, parent=parent) else: comment = Comment(post=post, text=text, author=request.user,) comment.save() return http.HttpResponseRedirect(request.path) else: comment_form = CommentForm() response = render(request, 'post.html', { 'post': post, 'comments': comments, 'comment_form': comment_form }) cookie_name = 'viewed_%s' % post.id if cookie_name not in request.COOKIES: response.set_cookie(cookie_name, '1', 18000) Post.objects.filter(slug=slug).update(views=F('views') + 1) return response
def show_blog(request, blog_id): stats = mytools.get_stats(request) try: this_blog = Blog.objects.get(pk = blog_id) except Blog.DoesNotExist: raise Http404 if request.POST: #Save and refresh the comments. response = HttpResponse() response['Content-Type'] = 'text/plain' user = request.POST.get('user') email = request.POST.get('email') this_content = request.POST.get('content') ctime = datetime.now() comment = Comment(user_name=user, email_addr=email, content=this_content, blog=this_blog, comment_time=ctime) comment.save() str_ctime = str(ctime).split('.')[0][:16] response.write(str_ctime) return response this_blog.scan += 1 this_blog.save() comments = Comment.objects.filter(blog__exact=this_blog) tags = Tag.objects.all() arch = mytools.get_arch() return render_to_response('blog.html', {'blog':this_blog, 'comments':comments, 'show_tags':tags, 'arch':arch, 'stats':stats} )
def handle(self, *args, **options): len_insert = options['comment'][0] if len_insert < 1: raise CommandError( f'argument = {len_insert} not in diapason: more then 1') else: article_queryset = Article.objects.all() # print(len(auther_queryset)) # print(auther_queryset[1]) # ps = self.comments(len_insert) # r_l = random.randint(0, len(article_queryset) - 1) l = len(article_queryset) ps = self.comments(len_insert) for p_in in ps: r_l = random.randint(0, l - 1) print(r_l) p = Comment(username=p_in[0], comment_text=p_in[1], article=article_queryset[r_l]) p.save(force_insert=True) self.stdout.write(self.style.SUCCESS(f'comment: {p} ')) self.stdout.write( self.style.SUCCESS(f'Success insert {len_insert} Comment'))
def delete_comment(id): comment = Comment.query.filter_by(id=id).first() blog_id = comment.blog Comment.delete_comment(id) flash('Comment has been deleted') return redirect(url_for('main.blog', id=blog_id))
def save(self): comment = Comment(name=self.name.data, email=self.email.data, content=self.content.data) comment.id = ObjectId() Post.objects.with_id(self.post_id.data).update(push__comments=comment) return comment
def add_comment(request, pk): p = request.POST #print p """output: <QueryDict: {u'body': [u'good eats'], u'csrfmiddlewaretoken': [u'F4ioZcjG9UQQlYzBVQWKAnhOdRavY2Wa'], u'author': [u'salin']}>""" if p.has_key("body") and p["body"]: author = "Anonymous" if p["author"]: author = p["author"] """ Create a form to edit an existing Comment """ comment = Comment(title=Post.objects.get(pk=pk)) """ Create a form to edit an existing Comment, but use POST data to populate the form. """ form_comment = CommentForm(p, instance=comment) form_comment.fields["author"].required = False """ Create, but don't save the new author instance. """ comment = form_comment.save(commit=False) """ Modify the author in some way.""" comment.author = author """ Comment Notification. """ notify = True if comment.author == "salin": notify = False """ Save the new instance.""" comment.save(notify=notify) return HttpResponseRedirect(reverse("post", args=[pk])) #d = {'test': comment} #return render_to_response("blog/test.html", d) else: html = "<html><body>Invalid Form!</body></html>" return HttpResponse(html)
def comment(request, post_id): author = request.POST['author'] content = request.POST['comment'] post = get_object_or_404(Post, pk=post_id) comment = Comment(author=author, comment=content, date=timezone.now(), post=post) comment.save() return HttpResponseRedirect(reverse('blog:detail', args=(post.id,)))
def add_comment(request, post_id): #add new comment to our post p = request.POST if p.has_key("text") and p["text"]: # if has no author then name him myself author = "Nemo" if p["comment_author"]: author = p["comment_author"] comment = Comment(post=Post.objects.get(pk=post_id)) # save comment form cf = CommentForm(p, instance=comment) cf.fields["comment_author"].required = False comment = cf.save(commit=False) # save comment instance comment.comment_author = author notify = True comment.save() return_path = redirect(request.META.get('HTTP_REFERER','/')) return return_path
def comment(request, post_id): p = get_object_or_404(Post, pk=post_id) if request.method == 'POST': if request.user.is_authenticated(): form = AuthenticatedCommentForm(request.POST) if form.is_valid(): cn = form.cleaned_data['name'] ce = form.cleaned_data['email'] ct = form.cleaned_data['comment'] c = Comment(post=p, name=cn, email=ce, text=ct) c.save() return HttpResponseRedirect( reverse('blog.views.post', args=(p.id,))) else: pass else: if request.user.is_authenticated(): form = AuthenticatedCommentForm() else: form = AnonymousCommentForm() cs = Comment.objects.filter(post=post_id).order_by('date') return render_to_response('blog/post.html', {'post': p, 'comments': cs, 'error_message': 'An error occurred.', 'form': form}, context_instance=RequestContext(request))
def blog_detail(request, pk): post = Post.objects.get(pk=pk) # Retrieves object with a given pk # If POST received, then new instance of a form is created form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post ) comment.save() # Save and add comment to form to context dictionary form = CommentForm() return HttpResponseRedirect('#') comments = Comment.objects.filter(post=post) # Get all comments in a post # Posts and comments are added to the context dictionary # Rendered to the template context = { "post": post, "comments": comments, "form": form, } return render(request, "blog_detail.html", context)
def detail(request, entry_id): if request.method == "POST": form = CommentForm(request.POST, error_class=DivErrorList) if form.is_valid(): author = request.user text = request.POST['text'] entry = entry = Entry.objects.get(pk=entry_id) pub_date = timezone.now() comment = Comment(author=author, entry=entry, text=text, pub_date=pub_date) comment.save() dates = Entry.get_dates() form = CommentForm() try: entry = Entry.objects.get(pk=entry_id) except Entry.DoesNotExist: raise Http404 comments = Comment.objects.filter(entry=entry) context = {'entry': entry, 'dates': dates, 'comments': comments, 'form': form} return render(request, 'blog/detail.html', context)
def blog_comment(request, blog_id): if request.method == 'POST': if 'post_id' not in request.POST: return JsonResponse({ 'status': -1, 'message': 'can not be empty' }, status=404) form = CommentForm(request.POST) if form.is_valid(): try: post = Post.objects.get(id=request.POST.get('post_id'), blog_id=blog_id) print(post) except: return JsonResponse( { 'status': -1, 'message': 'post does not exist' }, status=404) newCommment = Comment(text=form.cleaned_data['text'], post=post) newCommment.save() return JsonResponse({ 'status': 0, 'comment': { 'datetime': newCommment.datetime.strftime('%a %b %d %H:%M:%S %Y'), 'text': newCommment.text } }) else: return JsonResponse({'status': -1, 'message': 'can not be empty'})
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
def blog_detail(request, pk): post = Post.objects.get(pk=pk) # Once you’ve created the comment from the form, you’ll need to save it using save() and then query # the database for all the comments assigned to the given post...(continue here after 'forms.py') form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author = form.cleaned_data['author'], body = form.cleaned_data['body'], post = post ) comment.save() comments = Comment.objects.filter(post=post) context = { 'post': post, 'comments': comments, 'form': form, } return render(request, 'blog_detail.html', context) """
def blog_detail(request, pk): post = Post.objects.get(pk=pk) form = CommentForm() finished = False if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment(author=request.user, body=form.cleaned_data["body"], post=post) comment.save() form = CommentForm() finished = True comments = Comment.objects.filter(post=post) language = select_language(request) context = { "post": post, "comments": comments, "form": form, "language": language, "finished": finished } return render(request, "blog_detail.html", context)
def comment(request): fields = request.POST parent_post = Entry.objects.get(pk=fields['entry-id']) akismetData = {} akismetData['user_ip'] = request.META['REMOTE_ADDR'] akismetData['user_agent'] = request.META['HTTP_USER_AGENT'] akismetData['referrer'] = request.META['HTTP_REFERER'] akismetData['comment_type'] = 'comment' akismetData['comment_author'] = fields['who'] what = fields['what'].encode('ascii', 'ignore') is_spam = ak.comment_check(what, akismetData) new_comment = Comment(entry = parent_post, who = fields['who'], what = fields['what'], is_spam = is_spam) new_comment.save() post_url = "%s#%s%d" % (parent_post.get_absolute_url(), Comment.COMMENT_ANCHOR, new_comment.id) return HttpResponseRedirect( post_url )
def save(self, commit, Post_pk): comment = Comment(message=self.cleaned_data['message'], author=self.cleaned_data['author'], image=self.cleaned_data['image']) #이게 무슨 뜻인지?, comment.post_id = Post_pk if commit: comment.save() return comment
def add_comment(self, request): """ Add comment to an article """ # get post values article_id = request.POST.get('article_id', 0) comment_text = request.POST.get('comment_text', '') # if the comment has any value if comment_text.strip(): # create and save the comment article_obj = get_object_or_404(Article, id=article_id) client = get_object_or_404(Client, user=request.user) comment = Comment(client=client, article=article_obj, text=comment_text) comment.save() self.response = JsonResponse({ 'comment_text': comment.text, 'comment_username': comment.client.user.username, 'comment_date': comment.pub_date })
def blog_detail(request, pk): #get the post object from the DB post = Post.objects.get(pk=pk) #if the request is post then there will be a new comment #so we save this to the database form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment(author=form.cleaned_data['author'], body=form.cleaned_data['body'], post=post) comment.save() #get all the comments for this post comments = Comment.objects.filter(post=post) #render this as a template context = { "post": post, "comments": comments, "form": form, } return render(request, "blog_detail.html", context)
def comment(post_id): post = Post.query.get(post_id) if current_user.is_authenticated: form = CommentFormCurrent() if form.validate_on_submit(): comment = Comment(name=current_user.username, email=current_user.email, comment=form.comment.data, topic=post) db.session.add(comment) db.session.commit() send_comment_email(post_id, comment) return redirect(url_for("posts.post", id=post.id)) else: form = CommentFormAnonymous() if form.validate_on_submit(): comment = Comment(name=form.email.data[0:6] + "...@" + form.email.data.split("@")[-1], email=form.email.data, comment=form.comment.data, topic=post) db.session.add(comment) db.session.commit() send_comment_email(post_id, comment) return redirect(url_for("posts.post", id=post.id)) return render_template("comment.html", form=form, legend="Comment")
def blog_detail(request, pk): post = Post.objects.get(pk=pk) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment(author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post) comment.save() comments = Comment.objects.filter(post=post) context = { "post": post, "comments": comments, "form": form, } return render(request, "blog_detail.html", context)
def add_comment(form, entry): comment = Comment(author = form.cleaned_data['author'], body = form.cleaned_data['body'], entry = entry, is_publish = True) comment.save() send_comment_mail(comment)
def comment_create(request): article_id = request.POST.get('article_id', '') content = request.POST.get('content', '') article = Article.objects.get(id=article_id) author = Author.objects.get(name=request.session["author_name"]) comment = Comment(content=content, author=author, article=article) comment.save() return redirect('/articles/show?id=%d'%article.id)
def index(request): comment_name=request.POST['commentname'] comment_object=Comment(comment_text=comment_name,comment_type="article") comment_object.save(); return HttpResponse(comment_name)
def populate_comment(): posts = Post.objects.all() for post in posts: for n in range(10): ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut tempor neque. Vivamus venenatis, nisl sed cursus venenatis, velit enim feugiat est, sit amet lacinia lectus nulla at libero." comment = Comment(post=post, author="Author Name", body=ipsum) comment.save()
def setComment(request): if request.is_ajax(): form = CommentForm(request.POST) if form.is_valid(): p = Comment(blogid=request.POST.get('blogid'),name=request.POST.get('name'),email=request.POST.get('email'),website=request.POST.get('website'),content=request.POST.get('message'),date=datetime.datetime.now()) p.save() return HttpResponse(json.dumps({"code":1,"message":{"name":request.POST.get('name'),"message":request.POST.get('message')}})) else: return HttpResponse(json.dumps({"code":0,"message":[{"name":"name","error":form['name'].errors},{"name":"email","error":form['email'].errors},{"name":"website","error":form['website'].errors},{"name":"message","error":form['message'].errors}]}))
def comment(request, id): """ Add a comment to blog """ if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): data = form.cleaned_data comment = Comment() comment.comment = data['comment'] comment.blog_id = id comment.user_name = data['user_name'] comment.email = data['email'] comment.source_address = request.META['REMOTE_ADDR']# '192.168.2.8' comment.create_date = datetime.datetime.now() comment.save() blog = Blog.objects.get(id=id) if blog.comment_count is None: blog.comment_count = 0 blog.comment_count += 1 blog.save() if request.user.is_authenticated(): return HttpResponseRedirect('/adminshow/%s/' % id) else: return HttpResponseRedirect('/show/%s/' % id) else: blog = Blog.objects.get(id=id) comments = Comment.objects.filter(blog_id=id) return render_to_response('artical.html', {'blog' : blog, 'comments' : comments, 'form' : form}, context_instance=RequestContext(request, processors=[new_blog, blog_group])) else: return HttpResponseRedirect('/show/%s/' % id)
def entry_detail(request, year, month, day, slug, draft=False): date = datetime.date(*time.strptime(year+month+day, '%Y'+'%b'+'%d')[:3]) entry = get_object_or_404(Entry, slug=slug, created_on__range=( datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max) ), is_draft=draft) if request.method == 'POST' and entry.comments_allowed(): form = CommentForm(request.POST) if form.is_valid(): comment = Comment(**form.cleaned_data) comment.entry = entry if request.META['REMOTE_ADDR'] != '': comment.ip = request.META['REMOTE_ADDR'] else: comment.ip = request.META['REMOTE_HOST'] comment.date = datetime.datetime.now() comment.karma = 0 comment.spam = akismet(request, comment) comment.save() if (not comment.spam) and settings.BLOG_COMMENT_EMAIL: comment_email = "%s\n--\n%s\n%s\n%s" % (comment.comment, comment.name, comment.email, comment.website) send_mail('[Blog] %s' % entry.title, comment_email, comment.email, [entry.author.email], fail_silently=True) return HttpResponseRedirect(entry.get_absolute_url()) else: form = CommentForm() return render_to_response('blog/entry_detail.html', {'blog_title': settings.BLOG_TITLE, 'tags': Tag.objects.all(), 'object': entry, 'comment_form': form}, context_instance=RequestContext(request))
def add_comment(request, postslug): p = request.POST if p["body"]: author = request.user comment = Comment(post=Post.objects.get(slug=postslug)) cf = CommentForm(p, instance=comment) cf.fields["author"].required = False comment = cf.save(commit=False) comment.author = author comment.save() return HttpResponseRedirect('/blog/')
def comment(request,post_id): #post = get_object_or_404(Post,pk=post_id) comment_name=request.POST['commentname'] comment_object=Comment(comment_text=comment_name,comment_type="article",post_id_id=post_id) comment_object.save(); post = get_object_or_404(Post,pk=post_id) imageUrl= str(post.post_image) imageName = (imageUrl.split('/'))[3] #return HttpResponse(post_id) context = {'imageName':imageName,'article':post,'post_id':post_id } return render(request,'article.html',context)
def make(request, post_id): try: p = Post.objects.get(id=post_id) c = Comment(post=p, name=request.POST['name'], body=request.POST['body'], pub_date=datetime.datetime.now()) c.save() return HttpResponse("OK") except Post.DoesNotExist: return HttpResponse("ERROR")
def addComment(request, post_id): p = get_object_or_404(Post, pk=post_id) try: pk=request.POST.get('post_id', False) except (KeyError, Post.DoesNotExist): return render(request, 'blog/post.html', { 'post': p }) else: b = Comment(comment_text=request.POST.get('comment_text'),comment_autor=request.POST.get('email'),comment_date=timezone.now(),post_id = p.id) b.save() return HttpResponseRedirect(reverse('blog:post', args=(p.id,)))