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 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 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 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 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 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 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})
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
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 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(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())
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 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 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))
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 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 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 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_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 post_detail(request, slug=None): #retrieve instance = get_object_or_404(Post, slug=slug) if instance.published > 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) # print(get_read_time(instance.content)) print(get_read_time(instance.get_markdown())) 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 = { "instance": instance, "title": instance.title, "share_string": share_string, "comments": comments, "comment_form": form, } return render(request, "post_detail.html", context)
def add_comment_to_stop(request, pk): stop = get_object_or_404(Stop, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.stop = stop comment.save() return redirect('stop-detail', pk=comment.stop.pk) else: form = CommentForm() return render(request, 'stops/add_comment_to_stop.html', {'form': form})
def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.draft or instance.publish > timezone.now().date(): print(instance.draft) print(timezone.now().date()) if not request.user.is_staff or not request.user.is_superuser: raise Http404 initial_data = { 'content_type': instance.get_content_type, 'object_id': instance.id } comments = instance.comments comment_form = CommentForm(request.POST or None, initial=initial_data) if request.POST: if not request.user.is_authenticated: return redirect('/login/?next={slug}'.format(slug=slug)) if comment_form.is_valid(): c_type = comment_form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) object_id = comment_form.cleaned_data.get("object_id") content = 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(): parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=object_id, content=content, parent=parent_obj, ) return HttpResponseRedirect( new_comment.content_object.get_absolute_url()) context = { 'title': instance.title, 'instance': instance, 'comments': comments, 'comment_form': comment_form, } return render(request, 'post_detail.html', context)
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 test_invalid_form_not_exist_user(self): data = { 'object_id': self.commented_object.id, 'content_type': self.content_type.id, 'user': -1, 'parent': None, 'comment': 'test' } form = CommentForm(data=data) self.assertFalse(form.is_valid())
def test_invalid_form_empty_comment(self): data = { 'object_id': self.commented_object.id, 'content_type': self.content_type.id, 'user': self.test_user.id, 'parent': None, 'comment': '' } form = CommentForm(data=data) self.assertFalse(form.is_valid())
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 post_verify(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.user == request.user or request.user.is_superuser: return redirect('/') instance.my_photo = True instance.save() messages.success(request, "Verified and uploaded online. Thank you.") 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, "comments": comments, "comment_form": form, } return render(request, "post_detail.html", context)
def test_form_saves_values_to_instance_user_on_save(db, client): comment = factories.CommentFactory() comment_user = comment.user comment_form = CommentForm(user=comment_user, instance=comment_user, data={'content': 'has_changed'}) if comment_form.is_valid(): comment = comment_form.save() assert comment_user == comment else: assert False
def add_comment(request, article_id): if request.POST and ("pause", not request.session): form = CommentForm(request.POST) return_path = request.META.get('HTTP_REFERER', '/') if form.is_valid(): comment = form.save(commit=False) comment.comment_user = request.user comment.comment_article = Article.objects.get(id = article_id) form.save() request.session.set_expiry(600) request.session['pause'] = True return redirect(return_path)
def post(self, req, id): # 通过req。POST初始化一个有数据的cf对象 cf = CommentForm(req.POST) # 如果表单数据有效 if cf.is_valid(): # 通过cf的save方法得到模型类(Comment的实例) c = cf.save(commit=False) # 给模型类实例赋值 c.article = get_object_or_404(Article, pk=id) # 保存数据库 c.save() return redirect(reverse("blog:single", args=(id, )))
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 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 post_detail(request, slug=None): #instance = Post.objects.get(id=2) instance = get_object_or_404(Post, slug=slug) #title="Post 3" if instance.draft or instance.publish > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) print(get_read_time(instance.get_html())) # dont need these since i added CommentManager in models.py # content_type = ContentType.objects.get_for_model(Post) # obj_id = instance.id initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } comment_form = CommentForm(request.POST or None, initial=initial_data) if comment_form.is_valid() and request.user.is_authenticated(): 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(): 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( )) # this will update the form after commenting. comments = instance.comments # Comment.objects.filter_by_instance(instance) context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form": comment_form, } return render(request, "post_detail.html", context)
def posts_detail(request, slug): # instace = Post.objects.get(id=3) instance = get_object_or_404(Post, slug=slug) if instance.draft or instance.publish > timezone.now().date(): 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(): 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(): 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) messages.success(request, 'Your comment was added!') 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, } return render(request, "post_detail.html", context)
def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', published__year=year, published__month=month, published__day=day) categories = post.category.all() comments = post.comments.filter(parent__isnull=True).order_by('-created') if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_obj = PostComment.objects.get(id=parent_id) if parent_obj: replay_comment = comment_form.save(commit=False) replay_comment.parent = parent_obj new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() return redirect(request.path) else: comment_form = CommentForm() try: previous_post = post.get_previous_by_published() except post.DoesNotExist: previous_post = post try: next_post = post.get_next_by_published() except post.DoesNotExist: next_post = post return render( request, 'posts/post_detail.html', { 'post': post, 'categories': categories, 'comment_form': comment_form, 'comments': comments, 'previous_post': previous_post, 'next_post': next_post })
def post_detail(request, slug=None): 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 SAVE 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() #COMMENTS 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 #COMMUNITIES context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form":form, "tags": tags, } extra_context={ 'objects':Post.objects.all(), } return render(request, "stories/post_detail.html", context)
def post_detail(request, id=None): # return HttpResponse("<h1>Detail</h1>") # isntance = Post.objects.get(id=1) instance = get_object_or_404(Post, id=id) if not instance.published or instance.publish > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser or not request.user == instance.user: raise Http404 share_string = urllib.parse.quote(instance.content, safe='') #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 = request.POST.get("parent_id") except: parent_id = None if parent_id is not None: 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.order_by('-timestamp') context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form": form, } return render(request, "posts_detail.html", context)
def post_detail(request, slug=None): post = get_object_or_404(Post, slug=slug) if post.draft or post.publishDate > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(post.content) initial_data = { "content_type": post.get_content_type, "object_id": post.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 = post.comments contex = { "title": post.title, "post": post, "share_string": share_string, "comments": comments, "comment_form": comment_form, } return render(request, "posts/detail.html", contex)
def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) 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) # comments comments = instance.comments 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()) post_tags_ids = instance.tags.values_list('id', flat=True) similar_posts = Post.objects.active().filter(tags__in=post_tags_ids).exclude(slug=instance.slug) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by("-same_tags", '-publish')[:4] context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form": form, "similar_posts": similar_posts, } return render(request, "post_detail.html", context)
def view_post(request, pk): current_page = 'view-post' try: post = Post.objects.get(pk=pk) except: raise Http404 if not (request.user == post.user or request.user in Friend.objects.friends(post.user)) or request.user in Block.objects.blocking(post.user): reponse = HttpResponse("Permission denied.") reponse.status_code = 403 return reponse initial_data = { 'content_type': post.get_content_type, 'object_id': post.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 redirect("posts:view_post",pk=pk) comments = Comment.objects.filter_by_instance(post) args = {'post': post, 'comments':comments, 'current_page': current_page, 'comment_form': comment_form, 'me': request.user.userprofile, } return render(request, 'posts/view_post.html', args)
def test_example_form(db, user, content, post_id, validity): comment = factories.CommentFactory() comment_user = comment.user comment_post_id = comment.post_id form = CommentForm(user=comment_user, post_id=comment_post_id, data={ 'user': user, 'content': content, 'post_id': comment_post_id }) assert form.is_valid() is validity
def post(self, request, *args, **kwargs): self.object = self.get_object() form = CommentForm(request.POST) if request.user.id == None: return HttpResponseRedirect(reverse('myaccount:login')) if form.is_valid(): comment = Comment(user=request.user, text=form.cleaned_data['text'], article=self.object, reply_id=form.cleaned_data.get('reply_id', 0), reply_user=form.cleaned_data.get( 'reply_user', '')) return self.form_valid(comment)
def detail(request,slug): product = get_object_or_404(Product,slug=slug,status='p') comment = Comment.objects.filter(product=product) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): newcomment = form.save(commit=False) newcomment.user = request.user newcomment.product = product newcomment.save() else: form = CommentForm() return render(request,'shop/detail.html',{'product':product,'comment':comment,'form':form})
def post(self, req, id): # name=req.POST.get('name') # email=req.POST.get('email') # url=req.POST.get('url') # content=req.POST.get('content') cf = CommentForm(req.POST) print(cf) if cf.is_valid(): res = cf.save(commit=False) res.article = get_object_or_404(Article, pk=id) res.save() return redirect(reverse('blog:single', args=(id, )))
def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.draft == True or instance.publish > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_str = quote_plus(instance.context) 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") # print(c_type) new_type = c_type.split("|") # print(new_type[0].strip()) content_type = ContentType.objects.get(app_label=new_type[0].strip(), model=new_type[1].strip()) 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 # Comment.objects.filter_by_instance(instance) context = { "title": instance.title, "instance": instance, "share_string": share_str, "comments": comments, "comment_form": form, } return render(request, "post_detail.html", context)
def comment_thread(request, id): #obj = Comment.objects.get(id=id) try: obj = Comment.objects.get(id=id) except: raise Http404( "Sorry we could not access the requested thread, please contact the admin" ) if not obj.is_parent: obj = obj.parent content_object = obj.content_object # Post that the comment is on content_id = obj.content_object.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, "form": form, } return render(request, "comment_thread.html", context)
def posts_detail(request, slug): instance = get_object_or_404(Post, slug=slug) if instance.draft or instance.publish > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote(instance.title) # to show the comments and save them initial_data = { "content_type": instance.get_content_type, "object_pk": instance.pk } 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) object_pk = form.cleaned_data.get('object_pk') content_data = form.cleaned_data.get("content") parent_object = None try: parent_pk = int(request.POST.get("parent_pk")) # print("Parent Id is ", parent_id) except: parent_pk = None if parent_pk: parent_qs = Comment.objects.filter(pk=parent_pk) if parent_qs.exists(): # and parent_qs.count == 1: parent_object = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_pk=object_pk, content=content_data, parent=parent_object, ) return HttpResponseRedirect( new_comment.content_object.get_absolute_url()) # comments stuff ends here # comments is the property in post model comments = instance.comments context = { 'instance': instance, 'share_string': share_string, 'comments': comments, 'comment_form': form, } return render(request, 'post_detail.html', context)
def post_details(request, slug=None, pk=None): # instance = get_object_or_404(Post,pk=pk) instance = get_object_or_404(Post, slug=slug) if instance.draft or instance.publish > timezone.now(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) # print(get_read_time(instance.content)) # print(count_words(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_for_model(instance.__class__) # 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 = Comments.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() # print(form.cleaned_data) new_comment, created = Comments.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 = { 'obj_details': instance, 'share_string': share_string, 'comments': comments, 'comment_form': form } return render(request, 'blog_app/post_details.html', context)
def comment_thread(request, id): #comment = get_object_or_404(Comment, id=id) try: comment = Comment.objects.get(id=id) except: raise Http404 me = request.user.userprofile if not (request.user == comment.content_object.user or request.user in comment.content_object.user.userprofile.friends): reponse = HttpResponse("Permission denied.") reponse.status_code = 403 return reponse initial_data = { 'content_type': comment.content_type, 'object_id': comment.object_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 redirect(comment.get_absolute_url()) args = { 'comment': comment, 'comment_form': comment_form, 'current_page': 'comment-thread', 'me': me, } return render(request, "posts/comment_thread.html", args)
def post_detail(request, slug): post = get_object_or_404(Post, pk=slug) if post.draft or post.publish > timezone.now().date(): user = request.user if not user.is_staff or not user.is_superuser: raise Http404 initial_data = { 'content_type': post.content_type, 'object_id': post.id, } comment_form = CommentForm(request.POST or None, initial=initial_data) if comment_form.is_valid(): # Users must be logged in to comment if not request.user.is_authenticated(): messages.success(request, 'User is not logged in.') return HttpResponseRedirect( reverse('posts:detail', args=(post.id, ))) parent_obj = None c_type = comment_form.cleaned_data.get('content_type') try: parent_id = int(request.POST.get('parent_id')) except TypeError: parent_id = None # Store the parent id if we are processing a reply # Confirm that the parent comment exists in the DB if parent_id: queryset = Comment.objects.filter(id=parent_id) if queryset.exists(): parent_obj = queryset.first() Comment.objects.get_or_create( user=request.user, content_type=ContentType.objects.get(model=c_type), object_id=comment_form.cleaned_data.get('object_id'), content=comment_form.cleaned_data.get('content'), parent=parent_obj, ) return HttpResponseRedirect(reverse('posts:detail', args=(post.id, ))) context = { 'post': post, 'comment_form': comment_form, } return render(request, 'posts/detail.html', context)
def post_detail(request, id=None): instance = get_object_or_404(Post, id=id) if instance.draft or instance.publish > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 initial_data = { "content_type": instance.get_content_type, "object_id": instance.id, } #comments = Comment.objects.filter_by_instance(instance) comment_form = CommentForm(request.POST or None, initial=initial_data) if comment_form.is_valid(): print(comment_form.cleaned_data) 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 ) if created: print("Yeah it worked") return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "comments": comments, "comment_form": comment_form, } return render(request, "posts/detail.html", context)
def post_detail(request, slug=None): # instance = Post.objects.get(id=3) instance = get_object_or_404(Post, slug=slug) if instance.draft or instance.publish > timezone.now().date(): if not request.user.is_superuser or not request.user.is_staff: raise Http404 share_string = quote_plus(instance.content) comments = Comment.objects.filter_by_instance(instance) # comment design here 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(): # print(form.cleaned_data) 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_form': form, 'comments': comments, 'share_string': share_string, 'instance': instance, } return render(request, 'post_detail.html', context)
def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) template_name = "blog/detail.html" comments = obj.comments initial_data = {"content_type": obj.get_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") if c_type == 'blog post': c_type = BlogPost content_type = ContentType.objects.get_for_model(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 redirect(new_comment.content_object.get_absolute_url()) #method 2 # comments = Comment.objects.filter_by_instance(obj) # method 1 # content_type = ContentType.objects.get_for_model(BlogPost) # obj_id = obj.id # comments = Comment.objects.filter(content_type = content_type, object_id = obj_id) # the above 3 lines are really just saying BlogPost.objects.get(id=obj.id) context = { "object": obj, "comments": comments, "comment_form": comment_form } return render(request, template_name, context)