def test_guest_name_has_to_be_present_for_anonymous_user(self): data = { 'body': self.body, 'post': self.post.id} form = CommentForm(data=data) self.assertFalse(form.is_valid()) self.assertIn(_("This field is required."), form.errors['guest_name'])
def post(self, request, **kwargs): slug = self.kwargs['slug'] article = Article.objects.filter(slug=slug).first() form = CommentForm(request.POST) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj ) return redirect('articles:detail', slug=article.slug)
def test_guest_name_is_not_required_for_logged_in_user(self): request = HttpRequest() request.user = self.AuthenticatedUser( username=self.faker.pronounceable_unique_id(length=30), password=self.faker.password(), email=self.faker.email()) data = { 'body': self.body, 'post': self.post.id} form = CommentForm(data=data, request=request) self.assertTrue(form.is_valid())
def test_save_anonymous_user(self): data = { 'body': self.body, 'post': self.post.id, 'guest_name': self.guest_name} form = CommentForm(data=data) self.assertTrue(form.is_valid()) comment = form.save() self.assertEqual(comment.body, self.body) self.assertEqual(comment.post, self.post) self.assertEqual(comment.guest_name, self.guest_name) self.assertLessEqual(comment.created_at, timezone.now())
def add_comment(request, post_id): post_id = int(post_id) post = get_object_or_404(Post, pk=post_id) context = { 'post': post, 'categories': Category.objects.all() } comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save() comment.owner = request.user comment.save() post.comment_set.add(comment) return redirect('post:get', post_id=post.pk) else: context['form'] = comment_form return render(request, 'post.html', context)
def comment_create(request, id=None): data = dict() article = Article.objects.get(id=id) form = CommentForm() now = time.time() if request.session.get('pause', False) and request.session.get('start_time', False) > now: messages.error(request, _('Ви вже залишили коментар, зачекайте хвилину.'), extra_tags='error') else: if request.is_ajax() and request.method == 'POST': form = CommentForm(request.POST) if form.is_valid() and request.user.is_authenticated(): comment = form.save(commit=False) comment.comments_article = article comment.comments_user = Profile.objects.get(pk=request.user.pk) # АБО comment.comments_from = auth.get_user(request) АБО comment.comments_from_id = auth.get_user(request).id comment.save() form = CommentForm() messages.success(request, _('Коментар добавлений успішно!'), extra_tags='success') request.session['pause'] = True request.session['start_time'] = time.time() + 20 comments = article.comments.all().order_by('-comments_create') current_page = Paginator(comments, 4) page_number = request.GET.get('page', 1) data['html_comments'] = render_to_string('partial_comments_list.html', {"comments": current_page.page(page_number)}, request=request) data['form_is_valid'] = True else: data['form_is_valid'] = False message = messages.get_messages(request) if message: data['html_messages'] = render_to_string('messages.html', {'messages': message}, request=request) context = {'form': form, 'article': article} data['html_form'] = render_to_string('partial_comment_form.html', context, request=request) return JsonResponse(data)
def comment(request,art_id): """保存评论""" if request.method == 'POST': if not art_id: return HttpResponse("You commit wrong!") art = Articles.objects.get(id=int(art_id)) form = CommentForm(request.POST) if form.is_valid(): comm_body = form.cleaned_data['comm_body'] Comment.objects.create(article_id=art,comm_body=comm_body) return HttpResponse("Thank you for you comment,It recoverd!") return HttpResponse("You don't commit anythings") elif request.method == 'GET': return HttpResponse("here")
def detail_view(request, poi_id): comment_form = CommentForm(request.POST or None) poi = Poi.objects.get(id=poi_id) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.poi = poi comment.save() return HttpResponseRedirect("/detail/%i" % poi.pk) return render_to_response( "misto.html", context_instance=RequestContext( request, {"poi": poi, "comment_form": comment_form, "comment_list": Comment.objects.filter(poi=poi).order_by("pk")}, ), )
def comment(request, blog_id): """ 提交评论 """ blog = Blog.objects.get_by_id(blog_id) if blog is None: return Http404 form = CommentForm(request.POST) if request.method == "POST": if form.is_valid(): cmt = form.post(blog) cmt.ip = get_ip(request) cmt.save() return HttpResponseRedirect("/blog/%s#cmt" % blog.id) return render_and_response(request, "blog/detail.html", {"blog": blog, "form": form})
def article_detail(request, id): # 取出相应文章 article = ArticlePost.objects.get(id=id) # 浏览量 +1 article.total_views += 1 article.save(update_fields=['total_views']) # 取出文章评论 comments = Comment.objects.filter(article=id) # 引入评论表单 comment_form = CommentForm() # 将markdown语法渲染成html样式 md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) article.body = md.convert(article.body) # 需要传递给模板的对象 context = { 'article': article, 'toc': md.toc, 'comments': comments, 'comment_form': comment_form } # 载入模板,并返回context对象 return render(request, 'article/detail.html', context)
def article_detail(request, id): article = ArticlePost.objects.get(id=id) print(article.avatar) # 浏览量 +1 article.total_views += 1 article.save(update_fields=['total_views' ]) # update_fields表名只有total_views发生改变,提升性能 # Markdown扩展 md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', # 目录扩展 ]) # 筛选评论 comments = Comment.objects.filter(article=id) article.body = md.convert(article.body) # 处理文章正文 article.tags = ArticleTag.objects.filter(article_id=id) comment_form = CommentForm() context = dict( article=article, toc=md.toc, comments=comments, comment_form=comment_form, ) return render(request, 'article/detail.html', context)
def article_detail(request, id): article = ArticlePost.objects.get(id=id) comments = Comment.objects.filter(article=id) article.total_views += 1 article.save(update_fields=['total_views']) md = markdown.Markdown(extensions=[ # 包含 缩写、表格等常用扩展 'markdown.extensions.extra', # 语法高亮扩展 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) article.body = md.convert(article.body) comment_form = CommentForm() # 过滤出所有的id比当前文章小的文章 pre_article = ArticlePost.objects.filter(id__lt=article.id).order_by('-id') # 过滤出id大的文章 next_article = ArticlePost.objects.filter(id__gt=article.id).order_by('id') # 取出相邻前一篇文章 if pre_article.count() > 0: pre_article = pre_article[0] else: pre_article = None # 取出相邻后一篇文章 if next_article.count() > 0: next_article = next_article[0] else: next_article = None context = {'article': article, 'toc': md.toc, 'comments': comments, 'comment_form': comment_form, 'pre_article':pre_article, 'next_article':next_article,} return render(request, 'article/detail.html', context)
def get_comment_form(obj): content_type = ContentType.objects.get_for_model(obj) comment_form = CommentForm(initial={ 'content_type': content_type.model, 'object_id': obj.pk, 'reply_comment_id': 0, }) return comment_form
def article_detail(request, id): article = ArticlePost.objects.get(id=id) comments = Comment.objects.filter(article_id=id) comment_form = CommentForm() # 包含 缩写、表格等常用扩展 #语法高亮显示 md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) article.body = md.convert(article.body) # article.body=markdown.markdown(article.body,extensions=['markdown.extensions.extra', # 'markdown.extensions.highlight', # 'markdown.extensions.toc',]) article.total_views += 1 article.save(update_fields=['total_views']) pre_article = ArticlePost.objects.filter(id__lt=article.id).order_by('-id') next_article = ArticlePost.objects.filter(id__gt=article.id).order_by('id') if pre_article.count() > 0: pre_article = pre_article[0] else: pre_article = None if next_article.count() > 0: next_article = next_article[0] else: next_article = None context = { 'article': article, 'toc': md.toc, 'comments': comments, 'comment_form': comment_form, 'pre_article': pre_article, 'next_article': next_article } return render(request, 'article/detail.html', context)
def article_detail(request, id): article = ArticlePost.objects.get(id=id) # 取出文章评论 comments = Comment.objects.filter(article=id) # 浏览量 +1 article.total_views += 1 article.save(update_fields=['total_views']) # 将markdown语法渲染成html样式 md = markdown.Markdown(extensions=[ # 包含 缩写、表格等常用扩展 'markdown.extensions.extra', # 语法高亮扩展 'markdown.extensions.codehilite', # 目录扩展 'markdown.extensions.toc', ]) article.body = md.convert(article.body) # 引入评论表单 comment_form = CommentForm() # 添加comments上下文 context = { 'article': article, 'toc': md.toc, 'comments': comments, 'comment_form': comment_form, } return render(request, 'article/detail.html', context)
def show_entry(request, entry_id): entry = get_object_or_404(Entry, id=entry_id) topic = entry.topic read_cookie_key = read_statistics_once_read(request, entry) entry_content_type = ContentType.objects.get_for_model(entry) comments = Comment.objects.filter(content_type=entry_content_type, object_id=entry.id, parent=None) context = {} context['previous_entry'] = Entry.objects.filter( created_date__gt=entry.created_date).last() context['next_entry'] = Entry.objects.filter( created_date__lt=entry.created_date).first() context['topic'] = topic context['entry'] = entry context['comments'] = comments.order_by('-comment_time') context['comment_form'] = CommentForm( initial={ 'content_type': entry_content_type.model, 'object_id': entry_id, 'reply_comment_id': 0 }) response = render(request, 'learning_logs/show_entry.html', context) response.set_cookie(read_cookie_key, 'true') return response
def blog_detail(request, blog_pk): # 博客文章 blog = get_object_or_404(Blog, pk=blog_pk) read_cookies_key = read_account_once_read(request, blog) blog_content_type = ContentType.objects.get_for_model(blog) #得到该博客的一级评论数据,不包括回复 comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk, parent=None) context = {} blog = get_object_or_404(Blog, pk=blog_pk) context['previous_blog'] = Blog.objects.filter( create_time__gt=blog.create_time).last() context['next_blog'] = Blog.objects.filter( create_time__lt=blog.create_time).first() context['blog'] = blog context['login_form'] = LoginForm() context['comments'] = comments.order_by('-comment_time') # #得到评论数,传给前端页面 # context['comment_count'] = Comment.objects.filter(content_type=blog_content_type,object_id=blog.pk).count() #初始化form中2个字段的值 context['comment_form'] = CommentForm( initial={ 'content_type': blog_content_type.model, 'object_id': blog_pk, 'reply_comment_id': 0 }) response = render(request, 'blog/blog_detail.html', context) response.set_cookie( read_cookies_key, 'true' ) # 阅读cookies标记 设置有效期 1: max_age=60 以秒为单位 2: expires=datetime对象 具体时间,到了时间就失效 return response
def blog_detail(request, blog_pk): blog = get_object_or_404(Blog, pk=blog_pk) read_cookie_key = read_statistics_once_read(request, blog) blog.content = markdown.markdown( blog.content, extensions=[ 'markdown.extensions.extra', # 拓展 'markdown.extensions.codehilite', # 语法高亮拓展 'markdown.extensions.toc', # 允许自动生成目录 ]) blog_content_type = ContentType.objects.get_for_model(blog) comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk, parent=None) context = {} context['blog'] = blog # 上下文 context['previous_blog'] = Blog.objects.filter( create_time__gt=blog.create_time).last() context['next_blog'] = Blog.objects.filter( create_time__lt=blog.create_time).first() context['comments'] = comments.order_by('-comment_time') context['comment_form'] = CommentForm( initial={ 'content_type': blog_content_type.model, 'object_id': blog_pk, 'reply_comment_id': 0 }) response = render(request, 'blog_detail.html', context) response.set_cookie(read_cookie_key, 'true') return response
def blog_detail(request, blog_pk): blog = get_object_or_404(Blog, pk=blog_pk) read_cookie_key = read_statistics_once_read(request, blog) blog_content_type = ContentType.objects.get_for_model(blog) comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.pk, parent=None) context = {} context['previous_blog'] = Blog.objects.filter( create_time__gt=blog.create_time).last() context['next_blog'] = Blog.objects.filter( create_time__lt=blog.create_time).first() context['blog'] = blog context['comments'] = comments.order_by("-comment_time") context['comment_form'] = CommentForm( initial={ 'content_type': blog_content_type, 'object_id': blog_pk, 'reply_comment_id': 0 }) response = render(request, "blog/blog_detail.html", context) #响应 response.set_cookie( read_cookie_key, 'true', ) #expires = detetime max_age=60 return response
def blog(request, blog_id): blog = Blog.objects.get(id=blog_id) # 阅读数统计 read_cookie_key = read_statistics(request, blog) # 上一篇下一篇 previous_page = Blog.objects.filter( pub_date__gt=blog.pub_date).last() # gte两篇文章同时发表,对于一个用户是不正确的,多用户有很可能 next_page = Blog.objects.filter(pub_date__lt=blog.pub_date).first() # 获取评论对象 blog_content_type = ContentType.objects.get_for_model(blog) comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog.id) context = { 'blog': blog, 'previous_page': previous_page, 'next_page': next_page, 'comments': comments, 'comment_form': CommentForm(initial={ 'content_type': blog_content_type.model, 'object_id': blog_id }), } response = render(request, 'blog/blog.html', context) response.set_cookie(read_cookie_key, 'true') return response
def postdetail(request, post_id): post = get_object_or_404(Post, id=post_id) post.read_num += 1 post.save(update_fields=['read_num']) post_content_type = ContentType.objects.get_for_model(post) comments = Comment.objects.filter(content_type=post_content_type, object_id=post_id, parent=None).order_by('-comment_time') data = { 'content_type': post_content_type.model, 'object_id': post_id, 'reply_comment_id': 0 } comment_form = CommentForm(initial=data) reply_form = CommentForm(initial=data) return render(request, 'bbs/postdetail.html', locals())
def article_detail(request, id): # 取出相应的文章 article = ArticlePost.objects.get(id=id) # 取出文章评论 comments = Comment.objects.filter(article=id) # 浏览量 +1 article.total_views += 1 article.save(update_fields=['total_views']) """ article.body = markdown.markdown(article.body,extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) """ md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) article.body = md.convert(article.body) # 添加comments上下文 comment_form = CommentForm() context = { 'article': article, 'toc': md.toc, 'comments': comments, 'comment_form': comment_form, } return render(request, 'article/detail.html', context)
def blog_detail(request, blog_pk): current_blog = get_object_or_404(Blog, pk=blog_pk) read_cookie_key = read_statistics_once_read(request, current_blog) blog_content_type = ContentType.objects.get_for_model(current_blog) comments = Comment.objects.filter(content_type=blog_content_type, object_id=blog_pk) context = {} context['blog_detail'] = current_blog #查询前一条博客和后一条博客 previous_blog = Blog.objects.filter( create_time__gt=current_blog.create_time).last() next_blog = Blog.objects.filter( create_time__lt=current_blog.create_time).first() context['previous_blog'] = previous_blog context['next_blog'] = next_blog #返回评论内容 context['comments'] = comments context['comment_form'] = CommentForm(initial={ 'content_type': blog_content_type.model, 'object_id': blog_pk }) response = render(request, 'mainsite/blog_detail.html', context) response.set_cookie(read_cookie_key, 'true') return response
def blog_detail(request, id): md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', TocExtension(slugify=slugify) ]) article = get_object_or_404(Blog, pk=id) article.content = md.convert(article.content) # 获取这篇文字的评论 ct = ContentType.objects.get_for_model(Blog) comment_list = Comment.objects.filter(content_type=ct, object_id=id, parent=None) form_data = { 'content_type': ct.model, 'object_id': id, 'reply_comment_id': 0, } comment_form = CommentForm(initial=form_data) context = { 'blog': article, 'blog_toc': md.toc, 'blog_types': BlogType.objects.all(), 'blog_comments': comment_list.all(), 'comment_form': comment_form, } response = render(request, 'blog_detail.html', context) return response
def tiezi_detail(request, tiezi_id): x = ContentType.objects.get_for_model(TieZi) y = get_object_or_404(TieZi, pk=tiezi_id) if not request.COOKIES.get('tiezi_%s_read' % tiezi_id): readnum,created = ReadNum.objects.get_or_create(content_type=x,object_id=tiezi_id) readnum.read_num +=1 readnum.save() date = timezone.now().date() readdetail,created = ReadDetail.objects.get_or_create(content_type=x,object_id=tiezi_id,date=date) readdetail.read_num +=1 readdetail.save() tiezi_content_type = ContentType.objects.get_for_model(TieZi) comment_all = Comment.objects.filter(content_type=tiezi_content_type,object_id=tiezi_id,parent=None) context={} #context['user'] = request.user context['comment_count'] =Comment.objects.filter(content_type=tiezi_content_type,object_id=tiezi_id).count() context['comment_all'] = comment_all context['tiezi'] = y context['comment_form'] = CommentForm(initial={'content_type': tiezi_content_type.model, 'object_id': tiezi_id,'reply_comment_id':0}) context['login_form'] = LoginForm() response = render(request,'tiezi_detail.html', context) response.set_cookie('tiezi_%s_read' % tiezi_id, 'true') return response
def comment_create(request, id=None): data = dict() article = Article.objects.get(id=id) form = CommentForm() now = time.time() if request.session.get( 'pause', False) and request.session.get('start_time', False) > now: messages.error(request, _('Ви вже залишили коментар, зачекайте хвилину.'), extra_tags='error') else: if request.is_ajax() and request.method == 'POST': form = CommentForm(request.POST) if form.is_valid() and request.user.is_authenticated(): comment = form.save(commit=False) comment.comments_article = article comment.comments_user = Profile.objects.get( pk=request.user.pk ) # АБО comment.comments_from = auth.get_user(request) АБО comment.comments_from_id = auth.get_user(request).id comment.save() form = CommentForm() messages.success(request, _('Коментар добавлений успішно!'), extra_tags='success') request.session['pause'] = True request.session['start_time'] = time.time() + 20 comments = article.comments.all().order_by('-comments_create') current_page = Paginator(comments, 4) page_number = request.GET.get('page', 1) data['html_comments'] = render_to_string( 'partial_comments_list.html', {"comments": current_page.page(page_number)}, request=request) data['form_is_valid'] = True else: data['form_is_valid'] = False message = messages.get_messages(request) if message: data['html_messages'] = render_to_string('messages.html', {'messages': message}, request=request) context = {'form': form, 'article': article} data['html_form'] = render_to_string('partial_comment_form.html', context, request=request) return JsonResponse(data)
def comment_thread(request, id=None): # instance = get_object_or_404(Comment, id=id) try: instance = Comment.objects.get(id=id) except: raise Http404 initial_data = { "content_type": instance.content_object.get_content_type, "object_id": instance.object_id, } comment_forms = CommentForm(request.POST or None, initial=initial_data) print(comment_forms.errors) if comment_forms.is_valid(): c_type = comment_forms.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = comment_forms.cleaned_data.get('object_id') content_data = comment_forms.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj, ) return HttpResponseRedirect(instance.get_absolute_url()) context = { "instance": instance, "comment_forms": comment_forms, } return render(request, 'comment_thread.html', context)
def post_comment(request, post_pk): # 先获取被评论的文章,因为后面需要把评论和被评论的文章关联起来。 # 这里我们使用了 Django 提供的一个快捷函数 get_object_or_404, # 这个函数的作用是当获取的文章(Post)存在时,则获取;否则返回 404 页面给用户。 post = get_object_or_404(Post, pk=post_pk) # HTTP 请求有 get 和 post 两种,一般用户通过表单提交数据都是通过 post 请求, # 因此只有当用户的请求为 post 时才需要处理表单数据。 if request.method == 'POST': # 用户提交的数据存在 request.POST 中,这是一个类字典对象。 # 我们利用这些数据构造了 CommentForm 的实例,这样 Django 的表单就生成了。 form = CommentForm(request.POST) # 当调用 form.is_valid() 方法时,Django 自动帮我们检查表单的数据是否符合格式要求。 if form.is_valid(): # 检查到数据是合法的,调用表单的 save 方法保存数据到数据库, # commit=False 的作用是仅仅利用表单的数据生成 Comment 模型类的实例,但还不保存评论数据到数据库。 comment = form.save(commit=False) # 将评论和被评论的文章关联起来。 comment.post = post # 最终将评论数据保存进数据库,调用模型实例的 save 方法 comment.save() # 重定向到 post 的详情页,实际上当 redirect 函数接收一个模型的实例时,它会调用这个模型实例的 get_absolute_url 方法, # 然后重定向到 get_absolute_url 方法返回的 URL。 return redirect(post) else: # 检查到数据不合法,重新渲染详情页,并且渲染表单的错误。 # 因此我们传了三个模板变量给 detail.html, # 一个是文章(Post),一个是评论列表,一个是表单 form # 注意这里我们用到了 post.comment_set.all() 方法, # 这个用法有点类似于 Post.objects.all() # 其作用是获取这篇 post 下的的全部评论, # 因为 Post 和 Comment 是 ForeignKey 关联的, # 因此使用 post.comment_set.all() 反向查询全部评论。 # 具体请看下面的讲解。 comment_list = post.comment_set.all() context = { 'post': post, 'form': form, 'comment_list': comment_list } return render(request, 'blog/detail.html', context=context) # 不是 post 请求,说明用户没有提交数据,重定向到文章详情页。 return redirect(post)
def contrl(request, posts): sen = Sentence.objects.order_by('-time') sentences = sen[0] if sen else [] page_num = request.GET.get('page', 1) tags = Tags.objects.all() form = CommentForm() # 最新评论 comment_list2 = Comment.objects.all().order_by('-time') num3 = comment_list2[5].time comment_list3 = Comment.objects.filter(time__gt=num3) # 获取分类 classify = request.GET.get('classify', 0) title = '凯多首页' # 如果用于选择网站前端,还是后端技术 if classify == '1': posts = Post.objects.all().filter(classify='网站前端') title = '网站前端' elif classify == '2': posts = Post.objects.all().filter(classify='后端技术') title = '后端技术' post = Post.objects.filter(tags=tags) # post = Post.objects.filter(tags=tags) p = Paginator(posts, 3) page = p.get_page(page_num) page_nums = p.num_pages current_page_num = page.number page_range = list( range(max(1, current_page_num - 2), min(current_page_num + 2, page_nums) + 1)) # posts = Post.objects.all() post_list = Post.objects.all().order_by('-readnum__look') # 按文章观看次数降序排列 num = post_list[5].read_num() num1 = post_list[1].read_num() context = {} context['page_range'] = page_range context['page_nums'] = page_nums context['tags'] = tags context['post_list'] = post_list context['num'] = num context['num1'] = num1 context['post'] = post context['posts'] = posts context['page'] = page context['form'] = form context['comment_list3'] = comment_list3 context['comment_list2'] = comment_list2 context['sentences'] = sentences context['posts'] = posts context['title'] = title context['classify'] = classify return context
def update_comment(request): # referer = request.META.get('HTTP_REFERER', reverse('home')) comment_form = CommentForm(request.POST, user=request.user) if comment_form.is_valid(): comment = Comment( user=comment_form.cleaned_data['user'], text=comment_form.cleaned_data['text'], content_object=comment_form.cleaned_data['content_object']) parent = comment_form.cleaned_data['parent'] if parent is not None: comment.root = parent.root if parent.root is not None else parent comment.parent = parent comment.reply_to = parent.user comment.save() # 发送邮件通知 comment.send_mail() # 返回数据 data = { 'pk': comment.pk, 'status': 'SUCESS', 'username': comment.user.get_nickname_or_username(), 'comment_time': comment.comment_time.timestamp(), 'text': comment.text, 'content_type': ContentType.objects.get_for_model(comment).model, 'reply_to': comment.reply_to.get_nickname_or_username() if parent is not None else '', 'root_pk': comment.root.pk if comment.root is not None else '', } else: data = { 'status': 'ERROR', 'message': list(comment_form.errors.values())[0][0] } return JsonResponse(data)
def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) content_type = ContentType.objects.get_for_model(self.model) context_data['form'] = CommentForm(initial={ 'content_type': content_type, 'object_id': self.object.id }) return context_data
def get_context_data(self, **kwargs): # 覆写 get_context_data 的目的是因为除了将 post 传递给模板外(DetailView 已经帮我们完成), # 还要把评论表单、post 下的评论列表传递给模板。 context = super(PostDetailView, self).get_context_data(**kwargs) form = CommentForm() comment_list = self.object.comment_set.all() context.update({'form': form, 'comment_list': comment_list}) return context
def post(self, request, *args, **kwargs): """提交评论""" comment_form = CommentForm(request.POST) target = request.POST.get('target') if comment_form.is_valid(): instance = comment_form.save(commit=False) instance.target = target instance.save() success = True return redirect(target) else: success = False context = {'success': success, 'form': comment_form, 'target': target} return self.render_to_response(context)
def get_comment_form(blog_pk, obj): initial = { "object_id": blog_pk, "content_type": ContentType.objects.get_for_model(obj).model, "reply_comment_id": 0 } comment_form = CommentForm(initial=initial) return comment_form
def get_context_data(self, **kwargs): kwargs.update({ 'comment_from': CommentForm(), 'comment_list': self.get_comments(), }) return super(PostView, self).get_context_data(**kwargs)
def qdetailView(request,id=None): qobj=get_object_or_404(Question,id=id) cqset=Comment.objects.filter(que=qobj) form=CommentForm() return render(request, "qa/qdetail.html",{"qobj" : qobj,"cqset":cqset,"form":form})
def post_comment(request,article_id): article = get_object_or_404(ArticlePost,id=article_id) # 处理 POST 请求 if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article new_comment.user = request.user new_comment.save() return redirect(article) else: return HttpResponse("表单内容有误,请重新填写。") # 处理错误请求 else: return HttpResponse("发表评论仅接受POST请求。")
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs.get(self.pk_url_kwarg, None) comment_form = CommentForm() context['comments']=Comment.objects.filter(article=pk) context['comment_form']=comment_form return context
def detailView(request, post_id): if not request.user.is_authenticated: return redirect("/login/") objects = Post.objects.filter(id=post_id) #objects = get_object_or_404(Post,id=post_id) content_type = ContentType.objects.get_for_model(Post) for obj in objects: obj_id = obj.id initial_data = { "content_type": content_type, "object_id": obj_id, } comment_form = CommentForm(request.POST or None, initial=initial_data) if comment_form.is_valid(): c_type = comment_form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = comment_form.cleaned_data.get('object_id') content_data = comment_form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj) return HttpResponseRedirect( new_comment.content_object.get_absolute_url()) comments = Comment.objects.filter(content_type=content_type, object_id=obj_id, parent=None) dict = { 'post': objects, 'comments': comments, 'comment_form': comment_form } return render(request, 'detail.html', dict)
def add_comment(request, post_id): """ Process add comment post request """ if request.method == 'POST': form = CommentForm(request.user, request.POST) if form.is_valid(): # get post object with id post = Post.objects.get(id=post_id) # set comment user, post instance and parent (comment type) form.instance.user = request.user form.instance.post = post form.instance.parent = post # insert comment comment = form.save() # if user is auth. approve comment directly and fill user data if request.user.is_authenticated(): # approve comment comment.approve() # fill user fullname, email data and save comment.fullname = "%s %s" %(request.user.first_name, request.user.last_name) comment.email = request.user.email comment.save() # if user not auth. create and send activation key with email else: # create activation key comment.activation_key = User.objects.make_random_password() comment.save() send_email_validation.delay(comment) # add success message messages.success(request, _("Comment created succesfully.")) # redirect to post detail page return redirect("post_detail", post_id=post_id) # if form is not valid render post detail for showing errors return detail(request, post_id, comment_form=form) else: return redirect("post_detail", post_id=post_id)
def detail(request, slug): qs_article = Article.objects.filter(slug=slug) article = qs_article.get() qs_article.update(views=article.views+1) comment_form = CommentForm(request.POST or None) article.comments = article.comment_set.filter(author__user__is_active=True, parent_comment=None, hidden=False) if request.user.is_authenticated(): reported_comments = Comment.objects.filter(report__reporter__user=request.user) if request.POST and comment_form.is_valid(): comment = comment_form.save(commit=False) account = Account.objects.filter(user=request.user).get() comment.author = account comment.parent_article = article if 'parent_comment' in request.POST: comment.parent_comment = Comment.objects.filter(pk=request.POST['parent_comment']).get() comment.parent_comment.author.to_accounts.create(from_account=account, category="comment", subject="Comment reply from " + str(comment.author) + "...", body=comment.text + '\n\n<a href="' + reverse('article_detail', kwargs={'slug': article.slug}) + '#comments">Read more here...</a>') if comment.parent_comment.author.alerts_subscribe: email = comment.parent_comment.author.user.email subject = "You've received a message on blog.chancegraff.me..." text_message = "Your account has received a new message on Chance Graff's blog. You may view this message after you've signed into your account by visiting this address: http://blog.chancegraff.me/messages" html_message = "Your account has received a new message on Chance Graff's blog. You may <a href='http://blog.chancegraff.me/messages'>view this message</a> after you've signed into your account." msg = EmailMultiAlternatives(subject, text_message, 'Chance Graff <*****@*****.**>', [email]) msg.attach_alternative(html_message, "text/html") msg.send() comment.total_score = 1 comment.save() author_vote = Vote.objects.create(voter=account, comment=comment, value=1) return redirect('comment_saved', slug=article.slug) else: reported_comments = None return render(request, 'article/detail.html', {'article': article, 'comment_form': comment_form, 'reported_comments': reported_comments,})
def comment_add(request): comment=Comments.objects.all().order_by('-datetime') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): cd = form.cleaned_data name = cd['name'] content = cd['content'] subject = cd['subject'] #datetime = cd['datetime'] cmt=Comments(name=name,content=content,subject=subject,datetime=datetime.datetime.now()) cmt.save() return HttpResponseRedirect('/comment/add/') else: form = CommentForm() return render_to_response('comment_add.html', {'form': form,'comment':comment}, context_instance=RequestContext(request))
def show_article(request, pk): article = get_object_or_404(Article, pk=pk) if request.method == 'GET': comment_form = CommentForm() else: comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.author = request.user comment.article = article #if comment_form.cleaned_data['parent_id'] == '': if request.POST['parent_id'] == '': # the root comment pass else: comment.parent = Comment.objects.get(id=request.POST['parent_id']) comment.save() comment_tree = Comment.objects.filter(article=article) return render(request, 'article/show_article.html', {'article':article, 'comment_form':comment_form, 'comment_tree':comment_tree})