def post_comment_ajax(request, object_id): try: entry = Entry.published_objects.get(pk=object_id) except: raise Http404 if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): r = re.compile('(\w+\s+\n)|[<>"=]', re.I) #r = re.compile('[\w\s\n]?', re.I) #r = re.compile('<a href=', re.I) if not r.search(form.cleaned_data['body']) == None: raise Http404 add_comment(form, entry) page = HttpResponseRedirect('/blog/comment/' + object_id + '/') page.set_cookie('commentName', form.cleaned_data['author'].encode('utf-8'), expires=cookie_expires_value(), path='/', domain=None, secure=None) return no_cache_page(page) else: form = CommentForm() page = render_to_response('entry_comment.html', {'comments': entry.published_comment_list(), 'entry': entry, 'form': form}) return no_cache_page(page)
def post_comment(request, year, month, day, slug): try: entry = get_entry(year, month, day, slug) except: raise Http404 if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): r = re.compile('(\w+\s+\n)|[<>"=]', re.I) #r = re.compile('<a href=', re.I) if not r.search(form.cleaned_data['body']) == None: return HttpResponseForbidden('<h1>403 Forbidden.</h1>') add_comment(form, entry) page = HttpResponseRedirect(entry.get_absolute_url()) page.set_cookie('commentName', form.cleaned_data['author'].encode('utf-8'), expires=cookie_expires_value(), path='/', domain=None, secure=None) return page else: form = CommentForm() return render_to_response('blog/entry_detail.html', dict(form=form, object=entry, do_display_comments=True, do_display_comment_form=True), context_instance=RequestContext(request)) return HttpResponseForbidden('<h1>403 Forbidden.</h1>')
def detail(request, p_id): context = RequestContext(request) tags = Tag.objects.all() context_dict = {'tags': tags} post = get_object_or_404(Post, id=p_id) context_dict['post'] = post comments = Comment.objects.filter(post=post) context_dict['comments'] = comments if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('detail', p_id=p_id) else: form = CommentForm() context_dict['comment_form'] = form return render_to_response('blog/detail.html', context_dict, context)
def article(request, article_pk, slug=None): article = get_object_or_404(Article, pk=article_pk, is_draft=False) # If slug is incorrect, "redirect friendly" to the correct link. if not slug or slug != article.slug: return http.HttpResponsePermanentRedirect(article.get_absolute_url()) if request.method == "POST": user = request.user if user.is_anonymous(): return http.HttpResponseForbidden() comment_form = CommentForm(request.POST, user=user) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.author = user if user.is_staff and user.is_superuser: comment.is_moderated = True comment.save() return redirect(comment.get_absolute_url()) else: comment_form = CommentForm() return render_to_response( "article.html", { "page_title": article.title, "article": article, "comment_form": comment_form, "comment_pk": request.GET.get("comment_pk"), }, context_instance=RequestContext(request), )
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 comment(req): if req.method == 'POST': form = CommentForm(req.POST) # 换成表单 if form.is_valid(): comment = form.save() return HttpResponseRedirect('/comment/') comment_list = Comment.objects.all() paginator = Paginator(comment_list, 10) num_pages = paginator.num_pages pages = range(1, num_pages + 1) width = num_pages * 34 # Make sure page request is an int. If not, deliver first page. try: page = int(req.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: comments = paginator.page(page) except (EmptyPage, InvalidPage): comments = paginator.page(paginator.num_pages) return render(req, 'comment.html', { 'comments': comments, 'tests': comment_list, 'pages': pages, 'current_page': int(page), 'width': width, })
def post_detail(request, slug): post = get_object_or_404(Post.pub, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.ip_address = request.META.get("REMOTE_ADDR", None) comment = form.moderate(comment) comment.save() email_body = "%s posted a new comment on the post '%s'." mail_managers("New comment posted", email_body % (comment.user_name, post)) return redirect('blog.views.post_detail', slug=post.slug) else: form = CommentForm() return render_to_response('blog/post_detail.html', { 'post': post, 'form': form, })
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_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) comments = post.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() # XXX: fix this, can't find post after submitting return HttpResponseRedirect(reverse('blog:post_detail', kwargs={'year': year, 'month': month, 'day': day, 'post': post})) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'comment_form': comment_form, 'similar_posts': similar_posts})
def comment(request, post_id): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): if not request.user.is_authenticated(): r = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR']) if not r.is_valid: return redirect('/blog/'+post_id+'/') # Invalid form entry f = form.save(commit=False); f.post_id = post_id if request.user.is_authenticated(): f.author_id = request.user.id f.author_name = '' f.author_email = '' f.save() email_msg = 'You have a new comment at http://www.jessicasteiber.com/blog/'+post_id+'/#comments' email_from = '*****@*****.**' email_to = ['*****@*****.**', '*****@*****.**'] # Send email notification send_mail('New Blog Comment - JessicaSteiber.com', email_msg, email_from, email_to) return redirect('/blog/'+post_id+'/#comments') # Go back to blog with new comment else: return redirect('/blog/'+post_id+'/') # Invalid form entry else: return redirect('/blog/'+post_id+'/') # Go back to blog
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 get_article(request,slug): try: article=Article.objects.get(slug=slug) except ObjectDoesNotExist: return HttpResponseRedirect('/') try: comments=Comment.objects.filter(article=article).order_by('-date','-id') except ObjectDoesNotExist: comments=None if request.method == 'POST': form = CommentForm(request.POST, **{'article':article,'ip':request.META['REMOTE_ADDR'],}) if form.is_valid(): comment=Comment() comment.comment = form.cleaned_data['comment'] comment.article = article if request.user.is_authenticated(): comment.user = request.user comment.ip=request.META['REMOTE_ADDR'] comment.save() return HttpResponseRedirect('/'+article.slug) else: form = CommentForm() return render_to_response('blog/article.html', { 'form': form, 'article': article, 'comments':comments, },context_instance=RequestContext(request))
def comment_post(request): try: if request.method == 'POST': comment_form = CommentForm(request.POST) print(comment_form) if comment_form.is_valid(): print(comment_form.cleaned_data) username = comment_form.cleaned_data['author'] email = comment_form.cleaned_data['email'] url = comment_form.cleaned_data['url'] content = comment_form.cleaned_data['comment'] article_id = comment_form.cleaned_data['article'] print(article_id) # 获取表单信息 # comment = Comment(id=article_id,username=username,email=email,content=content,article_id=article_id) comment = Comment(username=username, email=email, url=url, content=content, article_id=article_id) comment.save() print('后') else: return render(request, 'failure.html', {'reason': comment_form.errors}) else: return render(request, 'failure.html') except Exception as e: logger.error(e) return redirect(request.META['HTTP_REFERER'])
def index(request): entries = Blog.objects.all() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] comments = form.cleaned_data['comments'] isSpam = consume(comments) closeWriters(writer_1, writer_2) updateSpamScore(isSpam) updateSvm(collectionSpamScores, scores[0]) writeSpamScores(spamScoresFilename) if isSpam: return render_to_response('postFail.html', locals()) else: return render_to_response('postSuccess.html', locals()) else: form = CommentForm() return render_to_response('index.html', locals())
def view_entry(request, e_id): """ View Entry """ entry = Entry.objects.get(id=e_id) entry.parsed_content = mark_safe(entry.content) #bbcode.render_html(entry.content) msg = '' if(request.method == 'POST'): user_data= {'author': request.POST['author'] , 'email': request.POST['email'], 'message': request.POST['message'],'captcha': request.POST['captcha'] } #check captcha code = request.session['captcha_code'] if(request.user.is_authenticated()): #user auth witrh external account user_data['author'] = '%s %s '%(request.user.first_name, request.user.last_name ) if(request.session['backend'] == 'twitter'): user_data['author'] += '(@%s)'%(request.user.username) else: user_data['author'] +='(%s)'%(request.session['backend']) if(request.user.email == ''): user_data['email'] = '*****@*****.**'#request.user.email else: user_data['email'] = request.user.email logout(request) cf = CommentForm(user_data) if(cf.is_valid()): #Check Captcha if(''.join(code) == str.strip(str(request.POST['captcha'].upper()))): #save comment com = Comment() com.author = cf.cleaned_data['author'] com.content = cf.cleaned_data['message'] com.email = cf.cleaned_data['email'] com.entry = entry try: com.save() msg = 'Comment posted succesfully. Thanks.!' except: msg = 'Error saving your comment. Please try again.' else: msg = 'Wrong Captcha code. Please Try Again' else: msg = 'Error processing your comment. Please Try Again.' request.session['comment_posted_msg'] = msg return redirect('/blog/article/%s'%(e_id))#TODO put marker here to go to specific part of the html if('comment_posted_msg' in request.session): msg= request.session['comment_posted_msg'] del request.session['comment_posted_msg'] comments = entry.comment_set.filter(status=True) cf = CommentForm() t = get_template("entry.htm") c = RequestContext(request, {'entry': entry,'comments': comments, 'cform': cf, 'rn': random.randint(1,999999), 'msg': msg}) return HttpResponse(t.render(c))
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 lire_article(request, slug): """ Affiche un article complet, sélectionné en fonction du slug fourni en paramètre """ article = get_object_or_404(Article, slug=slug) comments = Comment.objects.filter(article=article) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): # ajouter la relation avec l'article comment = Comment() comment.pseudo = form.cleaned_data['pseudo'] comment.email = form.cleaned_data['email'] comment.contenu = form.cleaned_data['contenu'] comment.article = article comment.save() renvoi = True else: form = CommentForm() return render(request, 'blog/lire_article.html', locals())
def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # List of active comments for this post comments = post.comments.filter(active=True) if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() # List of similar poste post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags =Count('tags')).order_by('-same_tags', '-publish')[:4] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments , 'comment_form': comment_form, 'similar_posts': similar_posts})
def post(request, username, post_id): try: template = 'blog/post.html' args = {} required_post = Post.objects.get(id=post_id) if not required_post.visible and required_post.user != request.user: raise Http404() args.update({'post': required_post}) args.update({'comments': Comment.objects.filter(post=post_id)}) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Comment(post=Post.objects.get(id=post_id), user=User.objects.get(username=request.user.username), body=form.cleaned_data['body']).save() return HttpResponseRedirect('/' + username + '/post' + post_id) else: form = CommentForm() args.update({'form': form}) except: raise Http404() return render_to_response(template, args, context_instance=RequestContext(request))
def submit_comment(request, slug): """ Process the comment form """ post = get_object_or_404(Post.objects, slug=slug) form = CommentForm(request.POST, auto_id="%s", prefix="CommentForm") if form.is_valid() and post.allow_comments: comment = form.save(commit=False) comment.ip_address = request.META.get("REMOTE_ADDR", None) comment.post = post comment.save() if comment.published: request.notifications.create(_("Your comment has been posted!"), "success") else: request.notifications.create(_("Your comment was posted, but it won't be published until approved."), "warning") if request.is_ajax(): response = render_to_response("blog/comment_submit.json", { "errors": None, "comment": comment, "post": post, "form": form, }, context_instance=RequestContext(request), mimetype="application/json") else: response = HttpResponseRedirect(post.get_absolute_url()) if form.cleaned_data.get("remember", False): response.set_cookie("comment_author", value=comment.author) response.set_cookie("comment_email", value=comment.email) response.set_cookie("comment_url", value=comment.url) else: response.delete_cookie("comment_author") response.delete_cookie("comment_email") response.delete_cookie("comment_url") return response else: request.notifications.create(_("There were some errors with your comment submission."), "error") if request.is_ajax(): template = "blog/comment_submit.json" mimetype = "application/json" errors = simplejson.dumps(form.errors, cls=LazyEncoder, ensure_ascii=False) else: template = "blog/comment_submit.html" mimetype = "text/html; charset=utf-8" errors = form.errors return render_to_response(template, { "errors": errors, "comment": None, "post": post, "form": form, }, context_instance=RequestContext(request), mimetype=mimetype)
def forms(request, article_id): if request.POST: new_form = CommentForm(request.POST) if new_form.is_valid(): print(request.POST, new_form.errors, new_form.cleaned_data) comment = new_form.save(commit=False) comment.comment_article = Article.objects.get(id=article_id) new_form.save() return redirect('/article/get/%s/' % article_id)
def article_detail(request, pk): article = get_object_or_404(Article, pk=pk) form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.article = article comment.save() return redirect(article) return render(request, 'blog/articles/article_detail.html', {'form': form, 'object': article})
def view_post(request, slug): post = get_object_or_404(Post, slug=slug) form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect(request.path) return render_to_response('blog_post.html',{'post': post,'form': form,},context_instance=RequestContext(request))
def post(self, request, pk): # return HttpResponse(request.POST['entry_id']) form = CommentForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse("Your comment submitted successfully") else: self.kwargs["forms"] = form return self.render_to_response(self.get_context_data(forms=form))
def edit_comment(request, comid): context=RequestContext(request) com=Comment.objects.get(pk=comid) form= CommentForm(request.POST or None, instance=com) if form.is_valid(): form.save() return added(request) return render_to_response('blog/edit_comment.html', {'form':form, 'comid':comid}, context)
def get_form_context(request, entry): """ Post a comment. """ # Fill out some initial data fields from an authenticated user, if present initial = { } if request.user.is_authenticated(): initial["name"] = request.user.get_full_name() initial["email"] = request.user.email # If there are errors or if we requested a preview show the comment if request.method == 'POST': form = CommentForm(entry, request.POST, initial=initial) if form.is_valid(): # Create the comment comment = form.get_comment() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send( sender = comment.__class__, comment = comment, request = request ) for (receiver, response) in responses: if response == False: return django_comments.CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) comment.save() # Save the comment and signal that it was saved signals.comment_was_posted.send( sender = comment.__class__, comment = comment, request = request ) # Feedback --> check in the template for 'commented'. Users can comment # without having to log in so request.user.message_set can't be used return { 'commented' : True, # Return a fresh form 'form': CommentForm(entry, initial=initial) } else: if request.user.is_authenticated(): messages.error(request, _(u"Your comment could not be posted. Please correct the errors below.")) else: form = CommentForm(entry, initial=initial) return { 'commented': False, 'form': form }
def post(self, request, *args, **kwargs): self.object = self.get_object() form = CommentForm(object=self.object, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(self.object.get_absolute_url()) context = self.get_context_data(object=self.object, form=form) return self.render_to_response(context)
def post(self, request): a=request.POST.get('post') print a if request.GET: print "get" if request.POST: print "post" create_comment = CommentForm(request.POST) if create_comment.is_valid(): create_comment.save() return HttpResponseRedirect("/blog/"+str(a)+"/mainblog2/")
def test_valid_data(self): """ test valid data """ form = CommentForm( {"name": "Turanga Leela", "email": "*****@*****.**", "body": "Your blog sucks"}, entry=self.entry ) self.assertTrue(form.is_valid()) comment = form.save() self.assertEqual(comment.name, "Turanga Leela") self.assertEqual(comment.email, "*****@*****.**") self.assertEqual(comment.body, "Your blog sucks") self.assertEqual(comment.entry, self.entry)
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)
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = post if comment.post.author == request.user: comment.approve() comment.save() return redirect('blog:post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'comment_form.html', {'form': form})
def add_comment_to_post(request, pk): # we take the request and the primary key that links it comment to post post = get_object_or_404 (Post, pk=pk) # Get the object or the 404 meaning nothing was found if request.method == "POST": # someone has entered the form form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) # saved in DOM memory comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html',{'form':form})
def articles(request, param): ''' 文章方法 :param request: :param param: :return: ''' tag = Tag.objects.all() category = Category.objects.all() newest_article = Article.objects.filter().order_by('-create_date')[:5] if request.method == "POST": form = CommentForm(request.POST) # 判断form是否有效 print(request.POST) if form.is_valid(): if request.POST['pid'] == "None": pid = None else: pid = int(request.POST['pid']) instance = Comment.objects.create(username=request.POST['username'],email=request.POST['email'],content=request.POST['content'], article_id = int(request.POST['article']),pid_id = pid ,reply_who = request.POST['reply_who']) instance.save() try: if param == '': page = request.GET.get('page') contacts = paginator_func(Article.objects.all().values().annotate(count=Count('comment__article')).values(), 10, page) else: article = Article.objects.get(id=int(param)) article_tag_name = '' for t in article.tag.all(): article_tag_name = article_tag_name+ t.name + ',' article.page_view = article.page_view + 1 article.save() sql_comment = Comment.objects.filter(article = int(param)) list_comment = [] for q_cmt in sql_comment: for l_cmt in list_comment: if not hasattr(l_cmt, 'children'): setattr(l_cmt, 'children', []) if q_cmt.pid == l_cmt: l_cmt.children.append(q_cmt) if q_cmt.pid == None: list_comment.append(q_cmt) form = CommentForm() return render(request, "article.html", locals()) except: return render(request, "404.html", {"error" : "提交链接非法."})
def article(request, pk): obj = Article.objects.get(pk=pk) if request.method == 'POST': if request.POST.get('like_count', None): obj.count += 1 obj.save() else: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.article = obj comment.save() comments = Comment.objects.filter(article=obj) context = {'article': obj, 'comments': comments} return render(request, 'blog/article.html', context)
def comment_post(request): try: comment_form = CommentForm(request.POST) if comment_form.is_valid(): # 获取表单信息 comment = Comment.objects.create(username=comment_form.cleaned_data['author'], email=comment_form.cleaned_data['email'], url=comment_form.cleaned_data['url'], content=comment_form.cleaned_data['comment'], article_id=comment_form.cleaned_data['article'], user=request.user if request.user.is_authenticated else None) comment.save() else: return render(request, 'failure.html', {'reason': comment_form.errors}) except Exception as e: logger.error(e) return redirect(request.META['HTTP_REFERER'])
def post(self, request, *args, **kwargs): obj = self.get_object() form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) # if comment.parent is not None: # comment.content, count = re.subn(r'^\[reply\].*?\[/reply\]', '', comment.content, 1) # if not comment.content: # return redirect(obj) # # if count is 0: # comment.parent = None comment.save() return redirect(obj)
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.user, request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = post comment.save() return redirect('blog:detail', pk=post.pk) else: form = CommentForm(request.user) return render(request, 'blog/post_comment.html', { 'form': form, 'post': post })
def detalle_post(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).order_by('-created_on') context = {"post": post, "comments": comments, "form": form} return render(request, "detalle_post.html", context)
def add_comment(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) form.author = request.user.username if form.is_valid(): form.cleaned_data['author'] = request.user.first_name comment = form.save(commit = False) comment.post = post comment.author = request.user.username comment.save() return redirect('post_detail',pk = post.pk) else: return HttpResponse("Invalid Entery") else: form = CommentForm() return render(request,'blog/comment_form.html',{'form':form})
def add_comment_to_post(request, pk): # get the post or return Error 404 post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): # get the comment, set the post and save it comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: # set an empty form id method is not POST form = CommentForm() return render(request, 'blog/comment_form.html', context={'form': form})
def add_comment_to_post( request, pk ): # To add a comment to a post we require a request and primary key. post = get_object_or_404( Post, pk=pk ) # Either get that object or 404 page and passing the post model and pk=pk if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user # set the post to the post we have gotten at the start of the function comment.post = post comment.save() # once save is hit on updates it redirects user to detail.html page return redirect('post_detail', pk=post.pk) else: # if the user doesnt want to submit something then show them the comments html page # because there is no comment being submitted the CommentForm() == all the comments for form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form})
def dispatch(self, request, *args, **kwargs): post = get_object_or_404(Post, slug=self.kwargs['slug']) comment = Comment.objects.filter(post=post, moder=True) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comm = form.save(commit=False) comm.author = request.user comm.post = post comm.save() else: form = CommentForm() return render(request, 'blog/post_detail.html', { "post": post, "form": form, "comment": comment })
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() # Redirects to "post_detail" view of respective post return redirect('post_detail', pk=post.pk) else: # Links to "comment_form.html" (template name not required by default, can be changed) form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def post_detail_view(request,year,month,day,post): post=get_object_or_404(Post,slug=post,status='publish',publish__year=year,publish__month=month,publish__day=day) comments=post.comments.filter(active=True) csubmit=False if request.method=='POST': form=CommentForm(request.POST) if form.is_valid(): new_comment=form.save(commit=False) new_comment.post=post new_comment.save() csubmit=True else: form=CommentForm() return render(request,'blog/post_detail.html',{'post':post,'form':form,'csubmit':csubmit,'comments':comments})
def blog_detail(request, pk): post = Post.objects.get(pk=pk) comments = Comment.objects.filter(post=post) 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() context = {'post': post, 'comments': comments, 'form': form} return render(request, 'blog_detail.html', context)
def post(request, pk): post = get_object_or_404(Post, pk=pk) form = CommentForm() if request.method == 'POST': # Gửi bình luận form = CommentForm(request.POST, author=request.user, post=post) if form.is_valid(): form.save() return HttpResponseRedirect(request.path) return render(request, 'blog/post.html', { "post": post, "form": form }) # link templates thep dạng 'tên app/tên file.html' #class PostDetailView(DetailView): #thay thế cho post cũ(*) ở trên #model = Post #template_name = 'blog/post.html'
def add_comment(request, pk): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = get_object_or_404(Blog, pk=pk) comment.date_time = timezone.now() comment.user = request.user comment.save() return redirect('blog-detail', pk=pk) else: form = CommentForm() return render(request, 'blog/add_comment.html', {'form': form})
def comment_new(request, pk): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.article_id = pk f.timestamp = timezone.now() f.save() path_post = request.session['path_post'] # print("path_post :" + str(f.article.author.mail)) send_mail('subject', path_post, '*****@*****.**', [f.article.author.mail]) return redirect('article-detail', pk=pk) else: form = CommentForm() return render(request, 'blog/comment_new.html', {'form': form, 'pk': pk})
def post_detail_view(request, year, post, pk): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, id=pk) comment_submit = False email_sent = False comment_form = CommentForm() if (request.method == 'POST'): if request.POST.get('share', '') == 'share': form = EmailShareForm(request.POST) if form.is_valid(): data = form.cleaned_data subject = 'Read, {}'.format(post.title) post_url = request.build_absolute_uri(post.get_absolute_url()) message = 'Hi {},\nPlease Read Post At :\n{}\nRegards,\nMorty Smith'.format( data['name'], post_url) send_mail(subject, message, '*****@*****.**', [data['to']]) email_sent = True elif request.POST.get('comment', '') == 'comment': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.name = request.user.get_full_name() new_comment.save(True) comment_submit = True form = EmailShareForm() comments = post.comments.filter(active=True) context_dict = { 'post': post, 'form': form, 'comment_form': comment_form, 'comment_submit': comment_submit, 'comments': comments, 'email_sent': email_sent } return render(request, 'blog/post_detail.html', context_dict)
def add_comment_to_post(request,pk): post=get_object_or_404(Post,pk=pk) # User click on a Post to comment, it sends a <pk> and it is used here # for redirection if request.method=='POST': # if user filled the form and hit Enter/Submit form=CommentForm(request.POST) # Get the values of Comment entered by user inside form object if form.is_valid(): comment=form.save(commit=False) # get the values inside comment object comment.post=post # Connect the comment to Post object comment.author=request.user.username #passes the current user's username as comment's author comment.save() # save comment into DB that is related to a particular Post via ForeignKey return redirect('post_detail',pk=post.pk) # if form is valid, post the comment the comment to the Post and redirect user to the specific post in # the blog he commented on. 'post_detail' is URL name else: form=CommentForm() # if method!=Post, present a form to fill i.e comment page return render(request,'blog/comment_form.html',{'form':form}) # render actual page to display in any case
def comment_new(request, post_pk): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = Post.objects.get(pk=post_pk) comment.save() messages.debug(request, '새로운 댓글을 등록했습니다.') messages.error(request, '새로운 댓글을 등록했습니다.') messages.success(request, '새로운 댓글을 등록했습니다.') return redirect('blog.views.post_detail', post_pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', { 'form': form, })
def comment_new(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() messages.info(request, "새 댓글이 등록되었습니다.") return redirect('blog.views.detail', pk) else: form = CommentForm() return render(request, "blog/form.html", { 'form': form, })
def add_comment_to_post(request, pk): # pk links the comment to the post post = get_object_or_404(Post, pk=pk) #get_list_or_404: get that object and if you couldn't find that page display 404 if request.method == 'POST': #form filled and submitted form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) #saves the form in the memory comment.post = post # object of the class comment.save() # saving it in DB return redirect('post_detail', pk=post.pk) else: # if the form is not submitted form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def add_comment(request, pk): post = get_object_or_404(Post, pk=pk) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = post.author comment.post = post comment = form.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', { 'form': form, 'post': post })
def blog_detail(request, id): post_all = Post.objects.all() post = get_object_or_404(Post, id=id) form = CommentForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() PostView.objects.get_or_create(user=request.user, post=post) context = { "form": form, "post": post, 'post_all': post_all, # 'trend':trend, } return render(request, 'blog-detail.html', context)
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_to_post(request, pk): ''' HERE WE ARE GRABBING THE OBJECT OF POST BECAUSE COMMENT IS TO BE PUT ON POST ''' post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def add_comment(request, post_id): post = get_object_or_404(Post, pk=post_id) form = CommentForm(request.POST) if form.is_valid(): body = form.cleaned_data['body'] comment = Comment() comment.post = post comment.user = request.user comment.body = body comment.save() ''' Always return an HttpResponseRedirect after successfully dealing with POST data. This prevents data from being posted twice if a user hits the Back button. ''' return HttpResponseRedirect(reverse('blog:detail', args=(post.slug,))) return render(request, 'blog/detail.html', {'post': post, 'form': form})
def post_detail(request, year, month, day, post): """ post detail view""" post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) #return render(request,'blog/post/detail.html', {'post': post}) # list of active comments for this post comments = post.comments.filter(active=True) if request.method == 'POST': # a comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # creates comment objecct but doesnt commit to database new_comment = comment_form.save(commit=False) # Assign the current post ot the comment new_comment.post = post #save the coment ot the database new_comment.save() comment_form = CommentForm() new_comment = False else: comment_form = CommentForm() new_comment = False # list of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude( id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by( '-same_tags', '-publish')[:4] return render( request, 'blog/post/details.html', { 'post': post, 'comments': comments, 'comment_form': comment_form, 'similar_posts': similar_posts, 'new_comment': new_comment })