def detail(request, pk): post = get_object_or_404(Post, pk=pk) if post.draft: if post.user != request.user: messages.error(request,'you have not permission to see that post',extra_tags='alert alert-danger') return redirect('posts:index') form=CommentForm(request.POST or None) # add comment if form.is_valid() and request.user.is_authenticated: instance=form.save(commit=False) instance.user=request.user instance.post=post parent=None try: parent_id=int(request.POST.get('parent_id')) except: parent_id=None if parent_id: query=Comment.objects.filter(id=parent_id) if query.exists(): parent=query.first() instance.parent=parent instance.save() return redirect('posts:detail',pk) return render(request, 'detail.html', {'post': post,'comment_form':form})
class NewsDetail(DetailView): model = Article template_name = 'news/article.html' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): self.comment_form = CommentForm(request.POST or None) # create filled (POST) or empty form (initial GET) if request.method == 'POST': self.comment_form.instance.article_id = self.get_object().id if self.comment_form.is_valid(): comment = self.comment_form.save(commit=True) client = Client() client.publish(self.get_object().get_cent_comments_channel_name(), comment.as_compact_dict()) cent_response = client.send() print('sent to channel {}, got response from centrifugo: {}'.format(self.get_object().get_cent_comments_channel_name(), cent_response)) return HttpResponse() # return HttpResponseRedirect(reverse('news:detail', args=[self.get_object().pk,])) else: return super().get(request, *args, **kwargs) # context = self.get_context_data() # return render('news/article.html', context) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = self.comment_form return context
def tamperWithForm(self, **kwargs): a = Article.objects.get(pk=1) d = self.getValidData(a) d.update(kwargs) f = CommentForm(Article.objects.get(pk=1), data=d) self.assertFalse(f.is_valid()) return f
class AddCommentView(TemplateView): @method_decorator(writeable_site_required) @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): commentable_id = self.args[0] self.commentable = get_object_or_404(self.commentable_model, id=commentable_id) self.comment = Comment(commentable=self.commentable, user=request.user) return super(AddCommentView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): self.form = CommentForm(instance=self.comment, prefix='comment') context = self.get_context_data() return self.render_to_response(context) def post(self, request, *args, **kwargs): self.form = CommentForm(request.POST, instance=self.comment, prefix='comment') if self.form.is_valid(): self.form.save() return redirect( self.commentable.get_absolute_url() + ('#comment-%d' % self.comment.id) ) else: context = self.get_context_data() return self.render_to_response(context) def get_context_data(self, **kwargs): context = super(AddCommentView, self).get_context_data(**kwargs) context['commentable'] = self.commentable context['commentable_name'] = self.get_commentable_name(self.commentable) context['comment_form'] = self.form context['submit_action'] = self.submit_action return context template_name = 'comments/add_comment.html'
def post_show(request, blog, slug): try: blog = Blog.objects.get(slug=blog) except: raise Http404(u'Não disponível') try: post = Post.published.get(slug=slug, blog=blog) except: raise Http404(u'Não disponível') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.submit_date = datetime.now() comment.user = None comment.site = Site.objects.get_current() comment.ip_address = request.META.get("REMOTE_ADDR", None) comment.content_type = ContentType.objects.get_for_model(post) comment.object_pk = post.id comment.save() return HttpResponseRedirect(reverse('post_show',args=(blog.slug,post.slug))) else: form = CommentForm() return render_to_response('blog/post_show.html', { 'post': post, 'blog': blog, 'form':form, }, context_instance=RequestContext(request))
def add_comment(request, object_type, id): skip = False if object_type == 'comicpage': object = get_object_or_404(ComicPage, pk=id) elif object_type == 'article': object = get_object_or_404(Article, pk=id) elif object_type == 'profile': object = get_object_or_404(Profile, pk=id) friend_status = get_relationship_status(object.user, request.user) if friend_status < 2 and object.user != request.user: skip = True elif object_type == 'tutorial': object = get_object_or_404(Tutorial, pk=id) elif object_type == 'episode': object = get_object_or_404(Episode, pk=id) elif object_type == 'video': object = get_object_or_404(Video, pk=id) if request.method == 'POST' and not skip: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.save() object.comments.add(comment) comments = object.comments.filter(is_deleted=False) return render_to_response('comments/list.html', {'comments':comments}, context_instance=RequestContext(request))
def after_transcribe_comment(request, document_id): """ Prompt for a comment after a transcription is done. """ document = get_object_or_404(Document, pk=document_id, type="post", scan__isnull=False, transcription__isnull=False) # Don't prompt for comment if they've already commented on this post. if document.comments.filter(user=request.user).exists() or (not settings.COMMENTS_OPEN): return redirect(document.get_absolute_url() + "#transcription") if document.transcription.complete: prompt_text = "Thanks for writing! I finished the transcription for your post." else: prompt_text = "Thanks for writing! I worked on the transcription for your post." form = CommentForm(request.POST or None, initial={ 'comment': prompt_text }) if form.is_valid(): comment, created = Comment.objects.get_or_create( document=document, comment=form.cleaned_data['comment'], user=request.user, ) if created: comment.document = document return redirect("%s#%s" % (request.path, comment.pk)) return render(request, "scanning/after_transcribe_comment.html", { 'document': document, 'form': form, })
def post(self, request, pk): self.object = get_object_or_404(Article, id=pk) comment = CommentForm(request.POST) commit_instance = comment.save() self.object.comments.add(commit_instance) self.object.save() return redirect(reverse('article_detail', args=[pk]))
def video_show(request, slug): try: video = Video.objects.get(slug=slug) except: raise Http404(u'Vídeo não encontrado.') related_videos = video.get_related_videos() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.submit_date = datetime.now() comment.user = None comment.site = Site.objects.get_current() comment.ip_address = request.META.get("REMOTE_ADDR", None) comment.content_type = ContentType.objects.get_for_model(video) comment.object_pk = video.id comment.save() return HttpResponseRedirect(reverse('video_show',args=[video.slug])) else: form = CommentForm() return render_to_response('videos/video_show.html', { 'video': video, 'related_videos':related_videos, 'form':form, }, context_instance=RequestContext(request))
def publication_detail(request, pk): try : object = Parution.objects.get(pk=pk) comments = Comment.objects.filter(parution=object) comment_form = CommentForm(request.POST or None) context = { "object":object, "comments":comments, } if comment_form.is_valid(): comment_text = comment_form.cleaned_data['comment'] print(comment_text) print(request.user) print(object) print(request.get_full_path()) print(object.get_absolute_url()) new_comment = Comment.objects.create_comment(user=request.user,text=comment_text,path=request.get_full_path(),parution=object) return HttpResponseRedirect(object.get_absolute_url()) return render(request,"blogdef/parution_detail.html",context) context["comment_form"]=comment_form return render(request,"blogdef/parution_detail.html",context) except : raise Http404
def edit_comment(request, problem_id, solution_id, comment_id): solution = Solution.objects.get(pk=solution_id) try: comment = Comment.objects.get(pk=comment_id) if comment.user.email != request.session['email']: return HttpResponseRedirect('/problems/'+str(problem_id)+'/show_solution/'+str(solution_id)) except Comment.DoesNotExist: raise Http404("Comment does not exist") if request.method == 'POST': comment_form = CommentForm(request.POST, instance=comment) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = UserProfile.objects.get(email=request.session['email']) comment.save() solution.comments.add(comment) return HttpResponseRedirect('/problems/'+str(problem_id)+'/show_solution/'+str(solution_id)) else: print comment_form.errors elif request.method == 'GET': c_edit = comment # c_edit.content = bleach.clean(c_edit.content, strip=True) comment_form = CommentForm(instance=c_edit) return render(request, 'problems/edit_comment.html', {'form': comment_form, 'problem_id': problem_id, 'solution_id': solution_id, 'comment':comment})
def sound(request, username, sound_id): try: sound = Sound.objects.select_related("license", "user", "user__profile", "pack", "remix_group").get(id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 user_is_owner = request.user.is_authenticated() and ( sound.user == request.user or request.user.is_superuser or request.user.is_staff or Group.objects.get(name="moderators") in request.user.groups.all() ) # If the user is authenticated and this file is his, don't worry about moderation_state and processing_state if user_is_owner: if sound.moderation_state != "OK": messages.add_message(request, messages.INFO, "Be advised, this file has <b>not been moderated</b> yet.") if sound.processing_state != "OK": messages.add_message(request, messages.INFO, "Be advised, this file has <b>not been processed</b> yet.") else: if sound.moderation_state != "OK" or sound.processing_state != "OK": raise Http404 except Sound.DoesNotExist: # @UndefinedVariable try: DeletedSound.objects.get(sound_id=sound_id) return render_to_response("sounds/deleted_sound.html", {}, context_instance=RequestContext(request)) except DeletedSound.DoesNotExist: raise Http404 tags = sound.tags.select_related("tag__name") if request.method == "POST": form = CommentForm(request, request.POST) if request.user.profile.is_blocked_for_spam_reports(): messages.add_message( request, messages.INFO, "You're not allowed to post the comment because your account has been temporaly blocked after multiple spam reports", ) else: if form.is_valid(): comment_text = form.cleaned_data["comment"] sound.comments.add(Comment(content_object=sound, user=request.user, comment=comment_text)) sound.num_comments = sound.num_comments + 1 sound.save() try: # send the user an email to notify him of the new comment! logger.debug( "Notifying user %s of a new comment by %s" % (sound.user.username, request.user.username) ) send_mail_template( u"You have a new comment.", "sounds/email_new_comment.txt", {"sound": sound, "user": request.user, "comment": comment_text}, None, sound.user.email, ) except Exception, e: # if the email sending fails, ignore... logger.error("Problem sending email to '%s' about new comment: %s" % (request.user.email, e)) return HttpResponseRedirect(sound.get_absolute_url())
def post(self, request, *args, **kwargs): if not request.user.is_authenticated(): return Response(status.HTTP_401_UNAUTHORIZED) ct = ContentType.objects.get_for_model(MODELS_MAPPINGS[kwargs['model']]) try: obj = ct.get_object_for_this_type(pk=kwargs['object_id']) except ObjectDoesNotExist: raise ErrorResponse(status.HTTP_404_NOT_FOUND) form = CommentForm(request.POST) if not form.is_valid(): raise ErrorResponse(status.HTTP_400_BAD_REQUEST) data = { 'content_type': ct, 'object_id': kwargs['object_id'], 'user': request.user, 'created': datetime.datetime.now(), 'content': form.cleaned_data['content'], } parent = form.cleaned_data['parent'] if parent: instance = parent.add_child(**data) else: instance = Comment.add_root(**data) if request.is_ajax(): return Response(status.HTTP_201_CREATED) return HttpResponseRedirect(obj.get_absolute_url())
def blog(request, slug): from comments.models import BLOG blog = Blog.objects.get(slug=slug) if not blog: raise Http404 form = CommentForm() if request.POST: form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.thing_id = blog.id comment.type = BLOG comment.thread_id, comment.reverse_thread_id = \ get_thread_id(type='blog', thing_id=blog.id) comment.save() return HttpResponseRedirect(reverse( 'blog.views.blog', args=(blog.slug,))) commentsPage, commentsIndex, commentsTree = \ get_comments_page(request, type=BLOG, obj=blog, rpp=10) return render_to_response(request, 'blog/blog.html', { 'blog': blog, 'commentForm': form, 'comments': commentsPage, 'commentsIndex': commentsIndex, 'commentsTree': commentsTree, })
def article_show(request, channel, slug): try: article = Article.published_detail.get(slug=slug, channel__slug=channel) article.views_count_last_week += 1 article.views_count += 1 article.save() except: raise Http404(u'Notícia não encontrada') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.submit_date = datetime.now() comment.user = None comment.site = Site.objects.get_current() comment.ip_address = request.META.get("REMOTE_ADDR", None) comment.content_type = ContentType.objects.get_for_model(article) comment.object_pk = article.id comment.save() return HttpResponseRedirect(reverse('article_show',args=(article.channel.slug,article.slug))) else: form = CommentForm() related_articles = article.get_related_articles() return render_to_response('articles/article_show.html', { 'article': article, 'related_articles': related_articles, 'form':form, 'is_article':True, }, context_instance=RequestContext(request))
def edit_comment(request, sub_id, comment_id): submission = Submission.objects.get(pk=sub_id) try: comment = Comment.objects.get(pk=comment_id) if comment.user.email != request.session['email']: return HttpResponseRedirect('/submissions/show/'+str(sub_id)) except Comment.DoesNotExist: raise Http404("Comment does not exist") if request.method == 'POST': comment_form = CommentForm(request.POST, instance=comment) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = UserProfile.objects.get(email=request.session['email']) # comment.content = bleach.clean(comment.content, strip=True) # comment.content = markdown.markdown(comment.content) comment.save() submission.comments.add(comment) return HttpResponseRedirect('/submissions/show/' + str(sub_id)) else: raise Http404("Form is not valid") elif request.method == 'GET': c_edit = comment # c_edit.content = bleach.clean(c_edit.content, strip=True) comment_form = CommentForm(instance=c_edit) return render(request, 'submissions/edit_comment.html', {'form': comment_form, 'sub_id': sub_id, 'comment':comment})
def postshow(request, id): if not request.user.is_authenticated(): raise Http404 instance = get_object_or_404(Post, id=id) queryset = Post.objects.get(id=id) 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(): 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") new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data ) if created: print("Yeah it work") # print(comment_from.cleaned_data) comments = instance.comments #comments = Comment.objects.filter(user=request.user) #comments = Comment.objects.filter(post=instance) context = { 'post': queryset, 'comments':comments, 'comment_from':form, } return render(request,"post/show.html",context)
def new(request, pk): note = get_object_or_404(Note, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.note = note comment.user = request.user comment.save() # add rep add_rep(request, c=comment) # create notification notify(comment=comment) d = { 'comment': comment, 'comment_form': CommentForm(), 'note': note, 'reply_form': ReplyForm(), 'static': settings.STATIC_URL, } comment_form = loader.get_template('comments/comment_form.html') comment_temp = loader.get_template('comments/comment.html') context = RequestContext(request, add_csrf(request, d)) data = { 'comment': comment_temp.render(context), 'comment_count': note.comment_count(), 'comment_form': comment_form.render(context), 'comment_pk': comment.pk, 'note_pk': note.pk, } return HttpResponse(json.dumps(data), mimetype='application/json') return HttpResponseRedirect(reverse('readings.views.detail', args=[reading.slug]))
def post_detail(request,slug=None): instance = get_object_or_404(Post,slug=slug) #comments = Comment.objects.filter_by_instance(instance) comments = instance.comments if(instance.draft or instance.publish > timezone.now().date()) and(not request.user.is_staff or not request.user.is_superuser): raise Http404 user = instance.user 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(): 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()) if created: print("Yeah it worked!") detail = { "title":"Detail", "post":instance, "user":user, "share_string": share_string, "comments":comments, "comment_form":form, } return render(request,"post_detail.html",detail)
def post(self, request, *args, **kwargs): form = CommentForm(request.POST) comment = form.save(commit=False) comment.resource = Resource.objects.filter( id=request.POST.get('resource_id')).first() comment.author = self.request.user comment.save() return HttpResponse("success", content_type='text/plain')
def post_detail(request, slug=None): today = timezone.now() # instance = Post.objects.get(id=3) instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 # # share_string = quote_plus(instance.content) # # # comments = Comment.objects.filter_by_instance(instance) # 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(): 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, "today": today, "comments": comments, "comment_form": form, # "share_string": share_string, } return render(request, "Post_detail.html", context)
def edit_comment(request, comment_id): if not request.user.is_authenticated(): return request_login(request) try: comment = Comment.objects.get(id=comment_id) except: raise Http404 if not request.user == comment.user: messages.add_message(request, messages.ERROR, "You can only edit your own comments.") return HttpResponseRedirect(reverse('proposal', args=[ str(comment.proposal.id), comment.proposal.slug ])) else: if request.method == "POST": if comment.is_new(): form = CommentForm(request.POST, instance=comment) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, "Comment edited.") return HttpResponseRedirect(reverse("proposal", args=[ str(comment.proposal.id), comment.proposal.slug ]) + "#comment_" + str(comment.id)) else: messages.add_message(request, messages.ERROR, "Invalid comment") else: messages.add_message(request, messages.ERROR, "You can only edit a comment in the " "first 5 minutes.") form = CommentForm(instance=comment) if comment.is_new(): if request.is_ajax(): extend_template = "ajax_base.html" else: extend_template = "base.html" return render(request, "edit_comment_form.html", {"form": form, "comment": comment, "extend_template": extend_template}) else: messages.add_message(request, messages.ERROR, "You can only edit a comment in the " "first 5 minutes.") return HttpResponseRedirect(reverse("proposal", args=[ str(comment.proposal.id), comment.proposal.slug ]) + "#comment_" + str(comment.id))
def post_detail(request, slug=None): # instance = Post.objects.get(id=1) print ("now in post_detail in views.py") print slug instance = get_object_or_404(Post, slug=slug) 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(): 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, ) # print ("-----------------------comment created") # print c_type # print type(new_comment.content_object) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) comments = instance.comments slugtest = slug context = { "slugtest": slugtest, "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form": form } return render(request, "post_detail.html", context)
def update(request, pk): comment = get_object_or_404(Comment, pk=pk) if request.method == "POST": form = CommentForm(request.POST, instance=comment) if form.is_valid(): form.save() return HttpResponseRedirect("%s#%s" % ( comment.link.get_absolute_url(), comment.id)) else: print form.errors
def add(request): print "Hit add request for comment" r = '/' if request.method =='POST': form = CommentForm(request.POST) #print repr(form.cleaned_data) #print request.POST if form.is_valid(): d = form.cleaned_data #print d['suid'] if suid_store.check(d['suid']): suid_store.add(d['suid']) suid_store.trim() c = Comment() p = d['parent'].split(':') pt = Ticket r = '/tickets/' print p[0] if p[0] in ('ticket','Ticket'): pt = Ticket r = '/tickets/' elif p[0] in ('comment','com','Comment','comments','Comments'): pt = Comment r = '/comments/' #print r #Insert other comment parents here try: p = pt.objects.get(id=int(p[1])) #print "Got model of type " + str(type(pt)) r += str(p.id) + '/' except: #print 'Cannot get model of type ' + str(type(pt)) return HttpResponse('Invalid Parent') #c.content_type = ContentType.objects.get_for_model(pt) c.parent = p c.submittedby = request.user.member c.submittedtime = datetime.datetime.now() c.content = d['content'] c.save() #print d['files'] fs = getfilesfromfields(d['files'],d['autofiles']) if fs: print fs c.attachedfiles.add(*fs) c.save() #print "Id for new comment", c.id #print r else: print "Suid seen before" else: print "Form is invalid" #print r return HttpResponseRedirect(r)
def test_invalid_form_no_object_id(self): data = { 'content_type': self.content_type.id, 'user': self.test_user.id, 'parent': None, 'comment': 'test' } form = CommentForm(data=data) self.assertFalse(form.is_valid())
def test_valid_form(self): data = { 'object_id': self.commented_object.id, 'content_type': self.content_type.id, 'user': self.test_user.id, 'parent': None, 'comment': 'test' } form = CommentForm(data=data) self.assertTrue(form.is_valid())
def comment_thread(request, id): # obj = get_object_or_404(Comment, id=id) try: obj = Comment.objects.get(id=id) except: raise Http404 if not obj.is_parent: obj = obj.parent # content_object = obj.content_object # content_id = obj.content_object.id # initial_data = { # "content_type": content_object.get_content_type, # "object_id": content_id, # } initial_data = { "content_type": obj.content_type, "object_id": obj.object_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()) context = { "comment": obj, "title": "Comments", "form": form, } return render(request, "comment_thread.html", context)
def edit_comment(request, comment_id=None, comment=None): form = CommentForm(request.POST or None, initial={ 'comment': comment.comment }) if form.is_valid(): comment.comment = form.cleaned_data['comment'] comment.save() return redirect(comment.get_absolute_url()) return render(request, "comments/edit_comment.html", { 'comment': comment, 'form': form, })
def test_invalid_form_not_exist_parent(self): data = { 'object_id': self.commented_object.id, 'content_type': self.content_type.id, 'user': self.test_user.id, 'parent': -1, 'comment': 'test' } form = CommentForm(data=data) self.assertFalse(form.is_valid())
def get_context_data(self, **kwargs): # 覆写 get_context_data 的目的是因为除了将 post 传递给模板外(DetailView 已经帮我们完成), # 还要把评论表单、post 下的评论列表传递给模板。 post = super(PostDetailView, self).get_object(queryset=None) context = super(PostDetailView, self).get_context_data(**kwargs) form = CommentForm() comment_list = self.object.comment_set.all() next_dictinfo = post.get_next_absolute_url() pre_dictinfo = post.get_pre_absolute_url() print next_dictinfo['url_info'] context.update({ 'form': form, 'comment_list': comment_list, 'next_url': next_dictinfo['url_info'], 'next_title': next_dictinfo['title'], 'pre_url': pre_dictinfo['url_info'], 'pre_title': pre_dictinfo['title'], }) return context
def detail(request, pk): post = get_object_or_404(Post, pk=pk) post.content = markdown.markdown(post.content, extensions={ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc' }) # 每次调用视图中的detail函数,则阅读量加1: post.increase_views() # 评论表单部分: 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 change_password(request, username): """ This function changes password of a user . It ask for current(old) password. It also keeps user logged in after successful password change. """ native_user = get_object_or_404(User, username=username) if request.user == native_user: if request.method == 'POST': password_change_form = PasswordChangeForm(native_user, request.POST) if password_change_form.is_valid(): user = password_change_form.save() update_session_auth_hash( request, user) # Important! To keep User Logged in. messages.success(request, 'Your password was successfully updated!') return HttpResponseRedirect( reverse('edit_profile', kwargs={'username': username})) else: messages.error(request, f'Something went wrong, try again!') return HttpResponseRedirect( reverse('edit_profile', kwargs={'username': username})) else: password_change_form = PasswordChangeForm(native_user) avatar_form = AvatarUploadForm() form = UserSignupForm() addpostform = PostForm() comments = Comment.objects.all() comment_form = CommentForm() user_profiles = UserProfile.objects.all() context = { 'password_change_form': password_change_form, 'addpostform': addpostform, 'avatar_form': avatar_form, 'form': form, 'comments': comments, 'comment_form': comment_form, 'user_profiles': user_profiles, } return render(request, 'user_profile/edit_profile.html', context) messages.info(request, f"You are not authorised to visit this page.") return HttpResponseRedirect( reverse('User Profile', kwargs={'username': request.user}))
def essay_detail(request, id): essay = get_object_or_404(Essay, id=id) essay.increase_views() md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) essay.body = md.convert(essay.body) essay.toc = md.toc form = CommentForm() comment_list = essay.essay_comment_set.all() context = { 'essay': essay, 'form': form, 'comment_list': comment_list, } return render(request, 'essay_post.html', context=context)
def get(self, request, pk): post = Post.objects.get(pk=pk) # 增加点击数 post.click_number += 1 post.save() md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', TocExtension(slugify=slugify), ]) post.body = md.convert(post.body) post.toc = md.toc form = CommentForm() comment_list = post.comment_set.all() return render(request, 'detail.html', { 'post': post, 'form': form, 'comment_list': comment_list, })
def detail(request, pk): post = get_object_or_404(Post, pk=pk) 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, 'blog/detail.html', context=context)
def detail(request, pk): """博客详情页""" post = get_object_or_404(Post, pk=pk) # 阅读量 +1 post.increase_views() # 记得在顶部引入 markdown 模块 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().order_by('-created_time') # 将文章、表单、以及文章下的评论列表作为模板变量传给 detail.html 模板,以便渲染相应数据。 context = {'post': post, 'form': form, 'comment_list': comment_list} return render(request, 'blog/detail.html', context)
def video_detail(request, cat_slug, vid_slug): """ Take a look at videos, check if user has a premium account. List free videos if possible. """ cat = get_object_or_404(Category, slug=cat_slug) video = get_object_or_404(Video, slug=vid_slug, category=cat) # Log that video page is viewed for analytics purpose page_view.send(request.user, page_path=request.get_full_path(), primary_obj=video, secondary_obj=cat ) if request.user.is_authenticated() or video.has_preview: try: is_member = request.user.is_member except: is_member = None if is_member or video.has_preview: comment_form = CommentForm() comments = video.comment_set.all() context = {"video": video, "comments": comments, "comment_form": comment_form, } return render(request, "videos/video_detail.html", context) else: # If viewer has no premium account, ask for it next_url = video.get_absolute_url() return HttpResponseRedirect("%s?next=%s" % ( reverse('account_upgrade'), next_url) ) else: # If viewer is not logged in ask to log in next_url = video.get_absolute_url() return HttpResponseRedirect("%s?next=%s" % ( reverse('account_login'), next_url) )
def detail(request, pk): post = get_object_or_404(Post, pk=pk) post.increase_views()# 阅读量+1 # 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 get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = CommentForm() comment_list = self.object.comment_set.exclude(pk__in = CommentExtension.objects.values_list('comment__pk', flat=True))\ .order_by('-created_time') comment_descendant_lst = CommentExtension.objects.filter( comment__post=self.object).order_by('-comment__created_time') comment_descendant_dic = {} md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc' ]) for item in comment_list: item.text = md.convert(item.text) #paginator paginator = Paginator(comment_list, 10) page = self.request.GET.get('page') try: comments = paginator.page(page) except PageNotAnInteger: comments = paginator.page(1) except EmptyPage: comments = paginator.page(paginator.num_pages) is_paginated = paginator.num_pages > 1 for item in comment_descendant_lst: item.comment.text = md.convert(item.comment.text) if item.under.pk in comment_descendant_dic: comment_descendant_dic[item.under.pk].append(item) else: comment_descendant_dic[item.under.pk] = [item] context.update({ 'form': form, 'comment_list': comments, 'comment_descendant_dic': comment_descendant_dic, 'page_obj': comments, 'is_paginated': is_paginated, 'paginator': paginator }) return context
def detail(request, pk): article = get_object_or_404(Article, pk=pk) # 浏览量加1 article.increase_views() # article.body = markdown.markdown(article.body, # extensions=[ # 'markdown.extensions.extra', # 'markdown.extensions.codehilite', # 'markdown.extensions.toc', # ]) # 记得在顶部导入 CommentForm form = CommentForm() # 获取这篇 post 下的全部评论 comment_list = article.comment_set.all() # 将文章、表单、以及文章下的评论列表作为模板变量传给 detail.html 模板,以便渲染相应数据。 context = {'post': article, 'form': form, 'comment_list': comment_list} return render(request, 'article/detail.html', context=context)
def get(self, req, id): # get_object_or_404方法可以从指定的数据库中得到指定的数据,没有则返回404 article = get_object_or_404(Article, pk=id) # 1、获取markdown实例 md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) # 2、使用makedown实例渲染指定字段 article.body = md.convert(article.body) # 3、将md的目录对象赋值给article article.toc = md.toc # 向页面传递一个评论表单 cf = CommentForm() return render(req, 'blog/single.html', locals())
def detail(request, pk): 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', ]) 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 get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = CommentForm() if self.request.user.is_superuser: comment_list = self.object.comment_set.filter( is_reply=False).order_by('-created_time') else: comment_list = self.object.comment_set.filter( is_reply=False, is_check=True).order_by('-created_time') min_id = Post.objects.all().last().id max_id = Post.objects.all().first().id context.update({ 'form': form, 'comment_list': comment_list, 'next_post': self.next_post(self.object.id, min_id), 'prev_post': self.prev_post(self.object.id, max_id) }) return context
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # content_type = ContentType.objects.get_for_model(Post) # obj_id = self.get_object().id # comments = Comment.objects.filter_by_instance(content_type=content_type, object_id=obj_id) instance = self.get_object() comments = instance.comments context['comments'] = comments initial_data = { 'content_type': instance.get_content_type, 'object_id': instance.id } comment_form = CommentForm(self.request.POST or None, initial=initial_data) context['comment_form'] = comment_form return context
def create_comment(request): """Create comment view.""" if request.method == 'POST': form = CommentForm(None, data=request.POST) if form.is_valid(): with transaction.atomic(): comment = form.save(commit=False) comment.user = request.user comment.content = json.loads(form.cleaned_data.get('content'))[ 'html'] # Quill form field's html form.save() create_notification(request, form) run_reputation_update(request.user) return redirect('post', pk=request.POST['post'])
def article_detail(request, article_id): # 取到对应的文章对象 article = Article.objects.get(id=article_id) # 渲染文章内容为markdown格式 article.content = markdown.markdown( article.content, extensions=[ # markdown语法扩展 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) # 取到作者对象 article_author = article.user # 取到文章的所有评论 comments = Comments.objects.filter(article=article_id) # 为评论引入表单 comment_form = CommentForm() # 标签云的所有标签 tags = Tag.objects.tag_article_num_list() # 获取与此文章相关的tag列表,获取的tag信息为tag名字和id article_tags = article.tag.all() article_tag_id = article.tag.values_list('id', flat=True) # 获取相关文章,标签一样的文章为相关文章,并将标签相关的文章进行聚合,取5篇 similar_articles = Article.objects.filter(tag__in=article_tag_id).exclude( id=article_id) similar_articles = similar_articles.annotate( same_tags=Count('tag')).order_by('-same_tags', '-id') # 文章访问量+1 article.click_count += 1 # 增加访问量之后保存进数据库 article.save(update_fields=['click_count']) context = { 'article': article, 'article_author': article_author, 'article_tags': article_tags, 'tags': tags, 'similar_articles': similar_articles, 'comments': comments, 'comment_fom': comment_form } return render(request, 'blog/detail.html', context=context)
def get_one_by_id(request, article_id): article = Article.objects.get(id=article_id) was_liked_by_user = False try: like = Like.objects.get(article=article_id, user=request.user.id) except ObjectDoesNotExist: like = None if isinstance(like, Like): was_liked_by_user = True likes_count = Like.objects.filter(article=article_id).count() comments_form = CommentForm() comments = fetch_comments_by_article_id(request, article_id, 1) result = { 'article': article, 'was_liked': was_liked_by_user, 'likes_count': likes_count, 'comments_form': comments_form, 'comments': comments } return render(request, 'articles/one.html', result)
def post(self, request, book_id): book = get_object_or_404(Book, pk=book_id) if request.user.is_authenticated: comment_form = CommentForm(request.POST, request.FILES) if comment_form.is_valid(): comment_instance = comment_form.save(commit=False) parent_id = request.POST.get('parent_id') if parent_id is not None: parent_obj = Comment.objects.get(pk=int(parent_id)) else: return self.get(request, book_id) comment_instance.parent_comment = parent_obj comment_instance.comment_user = request.user comment_instance.content_type = ContentType.objects.get_for_model( BookLog) comment_instance.content_object = BookLog.objects.get( booklog_book=book, booklog_owner=parent_obj.comment_user) comment_instance.object_id = book.id comment_form.save() comment_form.save_m2m() return HttpResponseRedirect(book.get_absolute_url()) return self.get(request, book_id)
def get(self, request, *args, **kwargs): """ Render the detail view for an object """ article = get_object_or_404(Article, slug=kwargs.get("slug")) context = { "article": article, } if request.user.is_authenticated & (request.user == article.author): context["article_author"] = request.user if request.user in article.user_favorites.all(): context["article_favorite"] = request.user if not request.user == article.author: commentform = CommentForm() context["comment_form"] = commentform return render(request, self.template_name, context)
def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) if self.request.user.is_authenticated(): initial_data = { 'content_type': self.object.get_content_type, 'obj_id': self.object.id } comment_form = CommentForm(initial=initial_data) voted = PostVotes.objects.filter(post=self.object, voter=self.request.user).exists() vote = PostVotes.objects.filter(post=self.object, voter=self.request.user).first() context['voted'] = voted context['comment_form'] = comment_form if voted: if vote.result > 0: context['enable'] = 'up' else: context['enable'] = 'down' return context
def detail(request,pk): # 获取文章详情 post = get_object_or_404(Post, pk=pk) # 阅读量+1 post.increase_views() # 代码高亮 md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', TocExtension(slugify=slugify), ]) post.body = md.convert(post.body) post.toc = md.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)
def poem(request, pk): poem_list = Post.objects.all().filter( category_id=3).order_by('-created_time') poem = get_object_or_404(Post, pk=pk) poem.body = markdown.markdown(poem.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() comment_list = poem.comment_set.all() context = { 'poem': poem, 'poem_list': poem_list, 'form': form, 'comment_list': comment_list } return render(request, 'blog/poem.html', context=context)
def detail(request, pk): post = get_object_or_404(Post, pk=pk) #调用阅读量函数 post.increase_views() #引入Markdown标记语言进行文本编辑 post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() #获取本篇文章下的全部评论 comment_list = post.comment_set.all() #将下列三个作为变量传给detail.html渲染 context = {'post': post, 'form': form, 'comment_list': comment_list} return render(request, 'blog/detail.html', context=context)
def detail(request, pk): article = get_object_or_404(Article, pk=pk) article.increase_views() article.body = markdown.markdown(article.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() # 获取所有的评论 comment_list = article.comment_set.all() # 将文章,表单,评论列表作为模版变量传给detail.html context = { 'article': article, 'form': form, 'comment_list': comment_list, } return render(request, 'blog/detail.html', context=context)
def nature(request, pk): nature_list = Post.objects.all().filter( category_id=4).order_by('-created_time') nature = get_object_or_404(Post, pk=pk) nature.body = markdown.markdown(nature.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() comment_list = nature.comment_set.all() context = { 'nature': nature, 'nature_list': nature_list, 'form': form, 'comment_list': comment_list } return render(request, 'blog/nature.html', context=context)
def comic(request, pk): comic_list = Post.objects.all().filter( category_id=2).order_by('-created_time') comic = get_object_or_404(Post, pk=pk) comic.body = markdown.markdown(comic.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() comment_list = comic.comment_set.all() context = { 'comic': comic, 'comic_list': comic_list, 'form': form, 'comment_list': comment_list } return render(request, 'blog/comic.html', context=context)
def detail(request, pk): post = get_object_or_404(Post, pk=pk) # 每次访客请求访问一次文章,阅读量就+1 post.increase_views() # 记得在顶部引入markdown 模块 # 注意这里我们给 markdown 渲染函数传递了额外的参数 extensions,它是对 Markdown 语法的拓展,这里我们使用了三个拓展,分别是 extra、codehilite、toc。 # extra 本身包含很多拓展,而 codehilite 是语法高亮拓展 post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() # 获取这篇文章下面的全部评论 comment_list = post.comment_set.all() # 将文章,表单,以及文章下的评论列表作为模板变量传给detail.html 模板,以便渲染相应数据。 context = {'post': post, 'form': form, 'comment_list': comment_list} return render(request, 'blog/detail.html', context=context)
def detail(request, pk): post = get_object_or_404(Post, pk=pk) #每被阅读一次,阅读量+1 post.increase_views() # 引入markdown post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc' ]) form = CommentForm() #获取这篇文章下的全部评论 comment_list = post.comment_set.all() #将文章,表单,评论列表作为变量床给detail.html模板 context = {'post': post, 'form': form, 'comment_list': comment_list} return render(request, 'blog/detail.html', context=context)
def detail(request, pk): article = get_object_or_404(Article, pk=pk) # 'markdown.extensions.extra':包含很多语法拓展 # 'markdown.extensions.codehilite': 语法高亮扩展 # 注: 实现代码高亮还需要两步,第一步如上,第二步安装第三方包pygments,第三步导入样式表文件,见base.html # 'markdown.extensions.toc': 自动生成目录 article.body = markdown.markdown(article.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) form = CommentForm() comment_list = article.comment_set.all() context = { "article": article, "form": form, "comment_list": comment_list, } return render(request, 'blog/detail.html', context=context)