def post(self, request, *args, **kwargs): json = YpSerialiser() form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user.get_profile() comment.save() photo_id = kwargs.get("id") if photo_id: photo = get_object_or_404(PhotosModels.Photos, pk=photo_id) photo.comments.add(comment) photo.save() else: return HttpResponse( simplejson.dumps({"id": 0, "status": 2, "txt": "комментарий не добавлен к изображению"}), mimetype="application/json", ) return HttpResponse( json.serialize( [comment], excludes=("object_id", "content_type"), relations={"author": {"fields": ("first_name", "last_name", "avatar")}}, ), mimetype="application/json", ) return HttpResponse(simplejson.dumps({"id": 0, "status": form._errors}), mimetype="application/json")
def post(self, request): form = CommentForm(request.POST or None) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') title_data = form.cleaned_data.get("title") 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, title=title_data, ) return redirect(new_comment.content_object.get_absolute_url())
def render_comment_form(context, obj): form = CommentForm(obj, auto_id='id_comment_form_%s') return { 'form': form, 'is_authnticated': context['user'].is_authenticated(), 'next_page': context['request'].get_full_path() }
def detail(request, pk): if not request.session.get('is_login', None): return redirect('/login/') post = get_object_or_404(Post, pk=pk) # 阅读量 +1 post.increase_views() post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) # 记得在顶部导入 CommentForm form = CommentForm() # 获取这篇 post 下的全部评论 # comment_list = post.comment_set.all() # 将文章、表单、以及文章下的评论列表作为模板变量传给 detail.html 模板,以便渲染相应数据。 context = { 'post': post, 'form': form, # 'comment_list': comment_list } return render(request, 'sharing/detail2.html', context=context)
def comment_edit(request, object_id, template_name='comments/edit.html'): comment = get_object_or_404(Comment, pk=object_id, user=request.user) if DELTA > comment.submit_date: return comment_error(request) if request.method == 'POST': form = CommentForm(request.POST, instance=comment) if form.is_valid(): form.save() return redirect(request, comment.content_object) else: form = CommentForm(instance=comment) return render(request, template_name, { 'form': form, 'comment': comment, })
def form_valid(self, form: CommentForm): comment = form.save(False) comment.user = self.request.user comment.article = self.object comment.save() return super().form_valid(form)
def get_context_data(self, **kwargs): 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 get_context_data(self, **kwargs): context = super(LinkDetail, self).get_context_data(**kwargs) comments = Comment.objects.filter(commented_to=self.object) comments = sorted(comments, key=lambda x: x.commented_on, reverse=True) context['comment_form'] = CommentForm( initial={'link_pk': self.object.pk}) context['object'] = self.object context['comments'] = comments return context
def get_context_data(self, **kwargs): # 覆写 get_context_data 的目的是因为除了将 post 传递给模板外(DetailView 已经帮我们完成), # 还要把评论表单、post 下的评论列表传递给模板。 context = super(PostDetailView, self).get_context_data(**kwargs) form = CommentForm() print(self, self.object, self.object.comment_set) print(type(self.object.comment_set)) comment_list = self.object.comment_set.filter(reply_to=None) context.update({'form': form, 'comment_list': comment_list}) return context
def get(self, request, topic_sn): try: topic_obj = Topic.objects.get(topic_sn=topic_sn) # 添加其他属性 topic_obj.like_num = TopicVote.objects.filter( vote=1, topic=topic_obj).count() topic_obj.dislike_num = TopicVote.objects.filter( vote=0, topic=topic_obj).count() topic_obj.favorite_num = TopicVote.objects.filter( favorite=1, topic=topic_obj).count() comments_obj = Comments.objects.select_related('author').filter( topic=topic_obj) now = datetime.now() md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) topic_obj.body = md.convert(topic_obj.body) # 传递给模板文章类型,用于评论表单区分 article_type = 'topic' # 评论 comment_form = CommentForm() if request.session.get('user_info'): topic_obj.thanks = TopicVote.objects.values_list( 'thanks').filter(topic=topic_obj, user_id=request.session.get('user_info') ['uid']).first() topic_obj.favorite = TopicVote.objects.values_list( 'favorite').filter(topic=topic_obj, user_id=request.session.get('user_info') ['uid']).first() # 使用F 自增此字段 增加一次阅读数量 Topic.objects.filter(topic_sn=topic_sn).update( click_num=F('click_num') + 1) # comments = topic_obj.comments.all() # toc=md.toc context = { 'article': topic_obj, 'comment_form': comment_form, # 生成树形评论 'comments': topic_obj.comments.all(), # 'comic_articles': comic_articles, # 'pre_article': pre_article, # 'next_article': next_article, 'article_type': article_type, 'toc': md.toc, } return render(request, 'topic/topic.html', context) except Topic.DoesNotExist: raise Http404("topic does not exist")
def post(self, request, *args, **kwargs): json = YpSerialiser() form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user.get_profile() comment.save() photo_id = kwargs.get('id') if photo_id: photo = get_object_or_404(PhotosModels.Photos, pk=photo_id) photo.comments.add(comment) photo.save() else: return HttpResponse(simplejson.dumps({ 'id': 0, 'status': 2, 'txt': 'комментарий не добавлен к изображению' }), mimetype="application/json") return HttpResponse(json.serialize( [comment], excludes=("object_id", "content_type"), relations={ 'author': { 'fields': ('first_name', 'last_name', 'avatar') } }), mimetype="application/json") return HttpResponse(simplejson.dumps({ 'id': 0, 'status': form._errors }), mimetype="application/json")
def read_book_detail(request, article_id): article = ReadBook.objects.get(id=article_id) # 传递给模板文章类型,用于评论表单区分 article_type = 'readbook' # 评论 comment_form = CommentForm() context = {'article': article, 'comment_form': comment_form, # 生成树形评论 'comments': article.comments.all(), 'article_type': article_type, } return render(request, 'readbook/book_detail.html', context=context)
def get_context_data(self, **kwargs): context = super(VlogDetailView, self).get_context_data(**kwargs) self.object.increase_views() # 传递给模板文章类型,用于评论表单区分 article_type = 'vlog' comment_form = CommentForm() extra_data = { 'comment_form': comment_form, # 生成树形评论 'comments': self.object.comments.all(), 'article_type': article_type, } context.update(extra_data) return context
def detail(request, pk): post = get_object_or_404(Post, pk=pk) post.increase_views() post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() comment_list = post.comment_set.all() context = {'post': post, 'form': form, 'comment_list': comment_list } return render(request, 'blog/detail.html', context=context)
def add_comment(request, article): """Helper-function for add comment""" success = None if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): success = True comment = form.save(commit=False) # Setting fields forms for save comment.article_id = article comment.approved = False comment.author = form.cleaned_data['author'] comment.email_author = form.cleaned_data['email_author'] comment.text = form.cleaned_data['text'] comment.save() form = CommentForm() else: form = CommentForm() return [form, success]
def article_detail(request, article_id): """ 文章详情的view :param article_id: 文章的id """ article = ArticlesPost.objects.get(id=article_id) article.increase_views() md = markdown.Markdown( extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ] ) article.body = md.convert(article.body) # 传递给模板文章类型,用于评论表单区分 article_type = 'article' # 评论 comment_form = CommentForm() # 根据漫画序号,取出漫画中前一条和后一条文章 if article.comic: next_article = ArticlesPost.objects.filter( comic_sequence__gt=article.comic_sequence, comic=article.comic, ).order_by('comic_sequence') pre_article = ArticlesPost.objects.filter( comic_sequence__lt=article.comic_sequence, comic=article.comic ).order_by('-comic_sequence') 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 comic_articles = article.comic.article.all().order_by('comic_sequence') context = {'article': article, 'comment_form': comment_form, # 生成树形评论 'comments': article.comments.all(), 'comic_articles': comic_articles, 'pre_article': pre_article, 'next_article': next_article, 'article_type': article_type, 'toc': md.toc, } return render(request, 'comic/article_detail.html', context=context) # 文章不属于任何漫画卷 else: context = {'article': article, 'comment_form': comment_form, # 生成树形评论 'comments': article.comments.all(), 'article_type': article_type, 'toc': md.toc, } return render(request, 'article/article_detail.html', context=context)
def render(self, context): obj = template.resolve_variable(self.commented_object, context) context[self.var_name] = CommentForm(initial={'content_type': ContentType.objects.get_for_model(obj).id, 'object_id': obj.id, 'next': obj.get_absolute_url()}) return ''
def post_detail(request, slug=None): """ Displays details of Post. """ # taggit # tag = Post.objects.filter( # tags__name__in=list(self.objects.tags.values_list('name', flat=True)) # ).exclude(id=self.object.id) # tag = Post..filter(pk=pk) # tag_names = [tag.name for tag in Tag.objects.all()] # print(tag_names) # import pdb; pdb.set_trace() instance = get_object_or_404(Post, slug=slug) recent_post = Post.objects.all().order_by( '-id')[:3] # 3 top list from descending order to time recent_comment = Comment.objects.all().order_by( '-id')[:3] # 3 top list from descending order to time top_tag = Tag.objects.all().order_by('-id')[:4] # for sidbar top tag # print(t) tag = instance.tags.all() num_tags = tag.count() print(tag.count()) # tag = instance if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated(): 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 HttpResponseRedirect( new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form": form, "tag": tag, "num_tags": num_tags, "recent_post": recent_post, "recent_comment": recent_comment, "top_tag": top_tag } # authentication if not request.user.is_authenticated(): return render(request, "user/post_detail.html", context) else: return render(request, "user/post_detail.html", context)
def test_notification_sending(self): """ Make the system send updates only on the object being followed (language vs. video). The following is taken directly from the ticket ----------------------------------------------- 1. Followers of a video (submitter + anyone who chose to follow the video) should: * Be listed as followers for each language of this video * Get notifications about any changes made to the video or any of the related languages. * Get notifications about any comments left on the video or any of the related videos. 2. Followers of a language (followers of language + transcriber(s)/translator(s) + editor(s) + anyone who chose to follow the language) should: * Get notifications about any changes made to the subtitles in this language, but not in any other language for the same video. * Get notifications about comments made on the subtitles in this language, but not in any other language for the video, nor on the video as a whole entity. """ # Video is submitted by self.user (pk 2, [email protected]) # The submitter is automatically added to followers via the # ``Video.get_or_create_for_url`` method. Here we do that by hand. self.assertEquals(0, Message.objects.count()) self.assertEquals(0, Comment.objects.count()) self.video.user = self.user self.video.user.notify_by_email = True self.video.user.notify_by_message = False self.video.user.save() self.video.followers.add(self.user) self.video.save() # Create a user that only follows the language user_language_only = User.objects.create(username='******', email='*****@*****.**', notify_by_email=True, notify_by_message=True) user_language2_only = User.objects.create(username='******', email='*****@*****.**', notify_by_email=True, notify_by_message=True) # Create a user that will make the edits user_edit_maker = User.objects.create(username='******', email='*****@*****.**', notify_by_email=True, notify_by_message=True) self.language.followers.clear() self.language.followers.add(user_language_only) latest_version = self.language.get_tip() latest_version.title = 'Old title' latest_version.description = 'Old description' latest_version.save() # Create another language lan2 = SubtitleLanguage.objects.create(video=self.video, language_code='ru') lan2.followers.add(user_language2_only) self.assertEquals(4, SubtitleLanguage.objects.count()) subtitles = self.language.get_tip().get_subtitles() subtitles.append_subtitle(1500, 3000, 'new text') version = pipeline.add_subtitles(self.video, self.language.language_code, subtitles, author=user_edit_maker, title="New title", description="New description") # Clear the box because the above generates some emails mail.outbox = [] # Kick it off video_changed_tasks(version.video.id, version.id) # -------------------------------------------------------------------- # How many emails should we have? # * The submitter # * All video followers who want emails # * All followers of the language being changed # * Minus the change author # # In our case that is: languageonly, adam, admin people = set(self.video.followers.filter(notify_by_email=True)) people.update(self.language.followers.filter(notify_by_email=True)) number = len(list(people)) - 1 # for the editor self.assertEqual(len(mail.outbox), number) email = mail.outbox[0] tos = [item for sublist in mail.outbox for item in sublist.to] self.assertTrue('New description' in email.body) self.assertTrue('Old description' in email.body) self.assertTrue('New title' in email.body) self.assertTrue('Old title' in email.body) # Make sure that all followers of the video got notified # Excluding the author of the new version excludes = list( User.objects.filter(email__in=[version.author.email]).all()) self.assertEquals(1, len(excludes)) followers = self.video.notification_list(excludes) self.assertTrue(excludes[0].notify_by_email and excludes[0].notify_by_message) self.assertTrue(followers.filter(pk=self.video.user.pk).exists()) for follower in followers: self.assertTrue(follower.email in tos) self.assertTrue(self.user.notify_by_email) self.assertTrue(self.user.email in tos) # Refresh objects self.user = User.objects.get(pk=self.user.pk) self.video = Video.objects.get(pk=self.video.pk) # Messages sent? self.assertFalse(self.video.user.notify_by_message) self.assertFalse( User.objects.get(pk=self.video.user.pk).notify_by_message) followers = self.video.followers.filter( notify_by_message=True).exclude(pk__in=[e.pk for e in excludes]) self.assertEquals(followers.count(), 1) self.assertNotEquals(followers[0].pk, self.user.pk) self.assertEquals(followers.count(), Message.objects.count()) for follower in followers: self.assertTrue(Message.objects.filter(user=follower).exists()) language_follower_email = None for email in mail.outbox: if user_language_only.email in email.to: language_follower_email = email break self.assertFalse(language_follower_email is None) # -------------------------------------------------------------------- # Now test comment notifications Message.objects.all().delete() mail.outbox = [] # Video comment first form = CommentForm( self.video, { 'content': 'Text', 'object_pk': self.video.pk, 'content_type': ContentType.objects.get_for_model( self.video).pk }) form.save(self.user, commit=True) self.assertEquals(1, Comment.objects.count()) self.assertEqual(len(mail.outbox), 1) emails = [] for e in mail.outbox: for a in e.to: emails.append(a) followers = self.video.followers.filter(notify_by_email=True) self.assertEquals(emails.sort(), [f.email for f in followers].sort()) followers = self.video.followers.filter(notify_by_email=False) for follower in followers: self.assertFalse(follower.email in emails) followers = self.video.followers.filter(notify_by_message=True) self.assertEquals(followers.count(), Message.objects.count()) for message in Message.objects.all(): self.assertTrue(isinstance(message.object, Video)) self.assertTrue(message.user in list(followers)) # And now test comments on languages Message.objects.all().delete() mail.outbox = [] form = CommentForm( self.language, { 'content': 'Text', 'object_pk': self.language.pk, 'content_type': ContentType.objects.get_for_model( self.language).pk }) form.save(self.user, commit=True) self.assertEquals( Message.objects.count(), self.language.followers.filter(notify_by_message=True).count()) followers = self.language.followers.filter(notify_by_message=True) # The author of the comment shouldn't get a message self.assertFalse(Message.objects.filter(user=self.user).exists()) lan2 = SubtitleLanguage.objects.get(pk=lan2.pk) lan2_followers = lan2.followers.all() for message in Message.objects.all(): self.assertTrue(isinstance(message.object, SubtitleLanguage)) self.assertTrue(message.user in list(followers)) self.assertFalse(message.user in list(lan2_followers))