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 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(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 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 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 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 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 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 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 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 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 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 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 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_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(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, 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 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 send_comment(request, article_id): if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.validate(): comment = Comment() comment_form.populate_obj(comment) comment.put() return redirect(reverse('display_article', kwargs={'article_id': article_id}))
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 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 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 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 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.comment_article = Articles.objects.get(id=article_id) form.save() request.session.set_expiry(60) request.session['pause'] = True return redirect('/articles/get/%s/' % article_id) # редирект на ту же статью на которой оставлен коммент
def post_detail_view(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) 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 add_comment_to_post( request, pk): #to add post we take request and pk to link comment to the post post = get_object_or_404(Post, pk=pk) #get object or 404 error page if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post #connect post to post object, 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)#ページが存在しなければ404を返すショートカット if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post#postの紐付け comment.save() return redirect('blog: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.post = post comment.save() return redirect('blog:post_detail', pk=post.pk) else: return HttpResponse('<h1>Comment is not valid</h1>') else: form = CommentForm() return render(request, 'comment_form.html', {'form': form})
def add_comment_to_post(request, pk): post = get_object_or_404(BlogPost, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.participant = request.user comment.save() url = reverse_lazy('blog:detail', kwargs={'slug': post.slug}) return redirect(url) else: form = CommentForm() return render(request, 'blog/detail_blog.html', {'form': form})
def comments_new(request, post_pk): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = get_object_or_404(Post, pk=post_pk) comment.save() ## 메세지 쓰는법 알아보기 messages.debug(request, '새로운 댓글을 등록했습니다.') return redirect(comment.post) ## redirect comment.post else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def add_comment_to_post(request, pk): ## take in a request and a pk ## pk that links the comment to the 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, slug): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:post_detail', slug=post.slug) else: form = CommentForm() template = 'blog/add_comment.html' context = {'form': form} return render(request, template, context)
def add_comment_to_post( request, pk ): #bu fonksiyona request ve asıl yorumu post ile bağlantılandıran birincil anahtarı argüman alırız post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) #gelen veriyi form değişkenine attık if form.is_valid(): #eğer form doğrulanmışsa comment = form.save(commit=False) comment.post = post # ----? comment nesnesini post nesnesine bağladık comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def comments_edit(request, post_pk, pk): comment = Comment.objects.get(pk=pk) if request.method == 'POST': form = CommentForm(request.POST, instance=comment) if form.is_valid(): comment = form.save(commit=False) comment.post = Post.get_object_or_404(pk=post_pk) comment.save() return redirect(comment.post) else: form = CommentForm(instance=comment) return render(request, 'blog/comment_form.html', { 'form': form, })
def add_comment_to_post(request, pk): post = get_object_or_404(Post, id=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/add_comment_to_post.html', {'form': form})
def addCommentToPost(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() return redirect('detail_post', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form})
def post_show(request, id): post = get_object_or_404(Article, id=id) article_comments = Comment.objects.filter(article=id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): instance = form.save() else: form = CommentForm() context = {"post": post, "comments": article_comments, "form": form} return render(request, "post.html", context)
def comment_new(request, post_pk): post = get_object_or_404(Post, pk=post_pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect(post) else: form = CommentForm() return render(request, 'blog/comment_new.html', {'form': form})
def post(self, request, pk): if 'pause' not in request.session: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comment_post = Post.objects.get(id=pk) form.save() request.session.set_expiry(60) request.session['pause'] = True return redirect('blog:detail', pk)
def comment_new(request, pk): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = get_object_or_404(Post, pk=pk) comment.save() return redirect('blog.views.detail', pk) else: form = CommentForm() return render(request, 'blog/form.html', { 'form': form, })
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() form = CommentForm() # empty form fields after submit 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() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comments(author=form.cleaned_data['author'], body=form.cleaned_data['body'], post=post) comment.save() form = CommentForm() comments = Comments.objects.filter(post=post) context = { 'form': form, 'post': post, 'comments': comments, } return render(request, 'blogs/blog_detail.html', context)
def blog_detail_view(request, id=''): try: post = BlogPost.objects.get(id=int(id)) except BlogPost.DoesNotExist: raise Http404 if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): is_owner = True if get_user_from_request(request) else False form.save_comment(post, is_owner) form = CommentForm() comments = post.blogcomment_set.all() t = loader.get_template("blog_detail.html") c = RequestContext(request, {'post': post}) c['comments'] = comments c['form'] = form return HttpResponse(t.render(c))
def post_detail(request, id): post = get_object_or_404(Post, id=id) comments = post.comments.all() form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.instance.post_id = id form.save() return redirect('/posts/%s' % id) return render(request, 'detail.html', { 'post': post, 'comments': comments, 'form': form, })
def one_blog_post(request, pk): if request.method == 'POST': Comment.objects.create( user=request.user, post=Post.objects.get(pk=pk), body=request.POST['body'], ) return redirect('one-post', pk) post = Post.objects.get(pk=pk) all_comments = Comment.objects.filter(post_id=pk) comment_form = CommentForm() context = { 'post': post, 'comment_form': comment_form, 'all_comments': all_comments, } return render(request, 'one_post.html', context)
def get_context_data(self, **kwargs): from blog.forms import CommentForm comment_form = CommentForm() user = self.request.user if user.is_authenticated: comment_form.fields["article_id"].initial = self.kwargs.get( 'article_id') article_comments = self.object.comment_list() kwargs['form'] = comment_form kwargs['article_comments'] = article_comments kwargs['comment_count'] = len( article_comments) if article_comments else 0 kwargs['next_article'] = self.object.next_article kwargs['prev_article'] = self.object.prev_article return super(ArticleDetailView, self).get_context_data(**kwargs)
def post(post_id): post = Post.query.get_or_404(post_id) like = post.thumbsup comments = Comment.query.filter(Comment.post_id == post.id) form = CommentForm() like_form = LikeForm() rate_form = RateForm() if like_form.validate_on_submit(): post.thumbsup += 1 db.session.add(post) db.session.commit() return redirect(f'/post/{post.id}') return render_template('post.html', post=post, comments=comments, form=form, like=like, like_form=like_form, rate_form=rate_form)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['prev_article'] = self.object.prev_article() context['next_article'] = self.object.next_article() comment_form = CommentForm() user = self.request.user # if user.is_authenticated: # comment_form.fields['email'].initial = user.email # 直接设置initial->value, 前端中这两个字段是hidden的 # comment_form.fields["name"].initial = user.username article_comments = self.object.get_comment_list() context['comment_form'] = comment_form context['article_comments'] = article_comments context['comment_count'] = len( article_comments) if article_comments else 0 return context
def postDetail(request, post_id, error=None, comment_form_from_create=None): post = Post.objects.get(pk=post_id) comments = Comment.objects.filter(post=post_id) comment_form = CommentForm() is_logged_in = request.user.is_authenticated context = { 'post': post, 'comments': comments, 'is_logged_in': is_logged_in, 'post_id': post_id } if error: context['error'] = error if comment_form_from_create: context['comment_form'] = comment_form_from_create else: context['comment_form'] = comment_form # if comment_form: # context['comment_form'] = comment_form return render(request, 'blog/detail.html', context)
def post_detail(request, year, month, day, post): ''' 文章详情页 :param request: :param year: :param month: :param day: :param post: :return: ''' 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) new_comment = None if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): # 通过表单直接创建新数据对象,但是不要保存到数据库中 new_comment = comment_form.save(commit=False) # 设置外键为当前文章 new_comment.post = post # 将评论写入数据库 new_comment.save() else: comment_form = CommentForm() # 显示相近标签的文章列表 # values_list方法返回指定的字段的值构成的元组,通过指定flat=True,让其结果变成一个列表比如[1, 2, 3, ...] post_tags_ids = post.tags.values_list('id', flat=True) # 获取当前相同标签的文章,并排除当前文章 similar_tags = Post.published.filter(tags__in=post_tags_ids).exclude( id=post.id) # 对每个文章的标签记数,生成新的字段same_tags,按照相同标签的数量,降序排列结果,获取前4篇文章 similar_posts = similar_tags.annotate(same_tags=Count('tags')).order_by( '-same_tags', '-publish')[:4] content = {} content['post'] = post content['comments'] = comments content['new_comment'] = new_comment content['comment_form'] = comment_form content['similar_posts'] = similar_posts return render(request, 'blog/post/detail.html', content)
def get(self, request, *args, **kwargs): slug = kwargs['slug'] post = get_object_or_404(Post, slug__iexact=slug) related_category_post = Post.objects.filter( category__name__iexact=post.category).exclude(title__iexact=post.title)[:3] tags = post.tags.split(",") comments = Comment.objects.all().filter( post__postId=post.postId, isApprove=True) context_dict = { 'post_tags': tags, 'post': post, 'related_category_post': related_category_post, 'form': CommentForm(), 'comments': comments } print(context_dict) return render(request, self.template_name, context_dict)
def get(self, request, *args, **kwargs): post = get_object_or_404(Post, pk=kwargs['pk']) is_liked = False if post.like.filter(id=request.user.id).exists(): is_liked = True images = Images.objects.filter(post=post) form = CommentForm() comments = Comment.objects.filter(post=post, reply=None).order_by('-id') if request.user.is_authenticated and request.user != post.author: post.viewed_users.add(request.user) context = { 'post': post, 'form': form, 'comments': comments, 'images': images, 'is_liked': is_liked, 'total_likes': post.total_likes() } return render(request, 'blog/post_detail.html', context)
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, '새로운 댓글을 등록했습니다.') # request를 받으므로 view 내에서만 쓸 수 있음. return redirect('blog,.post_detail', 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(): # it mean that we will save the form to memory, not to database, to modify it before save to database. 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})