def new_comment(request, post_id): """ Posts a new comment """ # Would use @login_required but can't handle POST request on return if not request.user.is_authenticated(): return redirect(reverse('accounts.views.login')) comment_of_interest = comment(user_id = request.user, post_id = post.objects.get(id=post_id)) form = commentForm(request.POST, instance=comment_of_interest) if request.method == "POST": # SPAM CHECK # bool_spam = spam_check(form['content'].value(), comment_of_interest, request) # if bool_spam: # return request.user.check_akismet(request) # Check for too frequent commenting (likely spam) comments_in_last_min = comment.objects.filter( time_created__gte=datetime.datetime.now()-datetime.timedelta(seconds=COMMENT_TIME_FRAME), user_id=request.user ) if len(comments_in_last_min)>=1: return render(request, 'rapid_comment.html', {'time_frame': COMMENT_TIME_FRAME, 'redirect_to': request.GET['next'], 'content': form['content'].value()} ) if form.is_valid(): temp = form.save(commit=False) parent = form['parent'].value() if parent == '': #Set a blank path then save it to get an ID temp.path = [] temp.save() temp.path = [temp.id] else: #Get the parent node node = comment.objects.get(id=parent) node.children += 1 #Keep track of children to display node.save() temp.depth = node.depth + 1 temp.path = node.path #Store parents path then apply comment ID temp.save() temp.path.append(temp.id) #Final save for parents and children temp.save() else: # Comment errors -- store in session for post_page view request.session['bad_comment_form'] = request.POST if 'next' in request.GET: return redirect(request.GET['next']) else: # Should never be entered, but remove session if so del request.session['bad_comment_form'] return redirect('/')
def post_comment(request, airticle_pk): #找到用户评论的文章 post = get_object_or_404(airticle, pk=airticle_pk) if request.method == 'POST': #将post的数据传给commentForm对象,用来进行表单提交到db forms = commentForm(request.POST) if forms.is_valid(): comments = forms.save(commit=False) #将post赋值给comments的外键 否则提交数据的时候,不会提交airticle_id(外键),会导致无法提交 comments.airticle = post comments.save() return redirect(post) else: comments_list = post.comment_set.all() context = { 'post': post, 'form': forms, 'comments_list': comments_list } return render(request, 'blog/detail.html', context=context) return redirect(post)
def single_post_view(request, id): try: last_post = Post.objects.last() post = Post.objects.get(id=id) comments = Comment.objects.filter(post=id).order_by('-id') comment_ids_list = [] for comment in comments: comment_ids_list.append(comment.id) replies = Reply.objects.filter(comment__in=comment_ids_list) form = commentForm(request.POST or None) if request.method == 'POST' and form.is_valid(): comment = request.POST.get('content') Comment.objects.create(content=comment, post=post, user=request.user) return redirect("/post/"+str(id)) except Post.DoesNotExist: return redirect("/") context = { 'post': post, 'comments': comments, 'comments_form': form, 'replies': replies, 'last_post': last_post } return render(request, 'posts_detail.html', context)
def comment(request, content_type, pk, comment_id=-1): object_type = ContentType.objects.get(model=content_type) ## If the post doesn't exist 404 them try: objecty = object_type.get_object_for_this_type(pk=pk) except: return HttpResponse(status=404) if request.method == 'POST': form = commentForm(request.POST) if form.is_valid(): #Save comment. commenttext = form.cleaned_data["commenttext"] ## If the comment is replying to another comment, thats fine, otherwise we set the parent to the root comment. if (form.cleaned_data["parent"]): parent = form.cleaned_data["parent"] else: parent = CommentRoot.objects.get(content_type=object_type, object_id=objecty.pk) commenter = request.user comment = Comment(commenttext=commenttext, commenter=commenter, parent=parent) comment.save() ########## I am so sorry. This redirect breaks the flexibility I was going for. This is very project. return HttpResponseRedirect('/project/' + str(objecty.pk)) else: #Form errors return render_to_response('commentform.html', dict(form=form, projectpk=pk)) else: #Make a new form form = commentForm() if comment_id == -1: form.fields['parent'].queryset = CommentRoot.objects.get( content_type=object_type, object_id=objecty.pk).get_descendants(include_self=False) else: from django import forms form.fields['parent'].widget = forms.HiddenInput() form.fields['parent'].initial = Comment.objects.get(pk=comment_id) return render_to_response('commentform.html', dict(form=form, projectpk=pk))
def comment(request, content_type, pk, comment_id=-1): object_type = ContentType.objects.get(model=content_type) ## If the post doesn't exist 404 them try: objecty = object_type.get_object_for_this_type(pk=pk) except: return HttpResponse(status=404) if request.method == 'POST': form = commentForm(request.POST) if form.is_valid(): #Save comment. commenttext = form.cleaned_data["commenttext"] ## If the comment is replying to another comment, thats fine, otherwise we set the parent to the root comment. if(form.cleaned_data["parent"]): parent=form.cleaned_data["parent"] else: parent = CommentRoot.objects.get(content_type=object_type, object_id=objecty.pk) commenter=request.user comment = Comment( commenttext=commenttext, commenter=commenter, parent=parent ) comment.save() ########## I am so sorry. This redirect breaks the flexibility I was going for. This is very project. return HttpResponseRedirect('/project/'+str(objecty.pk)) else: #Form errors return render_to_response('commentform.html', dict(form=form, projectpk=pk)) else: #Make a new form form = commentForm() if comment_id==-1: form.fields['parent'].queryset = CommentRoot.objects.get(content_type=object_type, object_id=objecty.pk).get_descendants(include_self=False) else: from django import forms form.fields['parent'].widget = forms.HiddenInput() form.fields['parent'].initial = Comment.objects.get(pk=comment_id) return render_to_response('commentform.html', dict(form=form, projectpk=pk))
def detail(request,pk): post = get_object_or_404(models.airticle,pk=pk) 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): post = self.get_object() context = super().get_context_data(**kwargs) form = commentForm(self.request.POST) comment_list = post.comment_set.all() cm_len = len(comment_list) data = { 'post': post, 'form': form, 'comment_list': comment_list, 'cm_len': cm_len } context.update(data) return context
def post_page(request, post_id): """ Displays a page with info about a certain post & a comment section """ post_of_interest = get_object_or_404(post, id=post_id) # If given a bad comment form, show form and errors if request.session.get('bad_comment_form'): comment_form = commentForm(request.session.get('bad_comment_form')) comment_form.is_valid() del request.session['bad_comment_form'] else: comment_form = commentForm # The comments to show will be determined by an AJAX call to 'load_comments' num_comments = len(comment.objects.filter(post_id=post_id)) post_comments = {} return render(request, 'post_page.html', {'post': post_of_interest, 'num_comments': num_comments, 'user_color_dict': get_user_model().COLORS, 'comment_form': comment_form, 'comment_tree': post_comments, })
def detail(request, pk): print("detail requested.") post = get_object_or_404(Post, pk=pk) post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc' ]) post.inc_views() post.save() form = commentForm(request.POST) comment_list = post.comment_set.all() cm_len = len(comment_list) recommended_post_list = recommend_post_content(post.pk) context = { 'post': post, 'form': form, 'comment_list': comment_list, 'cm_len': cm_len, 'recommended_post_list': recommended_post_list } return render(request, 'blog/detail.html', context=context)
def project(request, pk): ## If the post doesn't exist 404 them try: project = Project.objects.exclude(draft=True).get(pk=pk) except: return HttpResponse(status=404) object_type = ContentType.objects.get_for_model(project) projectfiles = fileobject.objects.filter(content_type=object_type, object_id=project.id) if project.enf_consistancy == False: raise Http404 else: mainthumb = project.thumbnail.get_thumb(650, 500) images = [] # Images in the project; will be handed to template # Get readme as first item in the list of texts to hand to the template. try: #Thus is in a try statement becouse the file backend might name the readme "ReadMe_1.md" or similar. Need to switch it out for "bodyfile" forighnkey at some point. readme = project.bodyFile htmlreadme = htmlobject.objects.get_or_create(fileobject=readme)[0] texts = [[htmlreadme, path.split(str(readme.filename))[1]]] except: texts = [] pass # norenders. this is the number of files in the project not rendered. We currently do nothing.. unless someone changed that and not this note. norenders = 0 for i in projectfiles: thumb = i.get_thumb(65, 50) renderer = i.filetype if renderer != "norender" and renderer != "text": images.append(thumb) if renderer == "norender": norenders += 1 if renderer == "text" and i != project.bodyFile: htmlmodel = htmlobject.objects.get_or_create(fileobject=i)[0] texts.append([htmlmodel, path.split(str(i.filename))[1]]) download = zippedobject.objects.get_or_create(project=project)[0] author = project.author from userProfile.models import userProfile authorprofile = userProfile.objects.filter(user=author)[0] try: authorpic = authorprofile.userpic.get_thumb(128, 128)[0] except: authorpic = False ## get the root comment of the project and use it to get all the projects comments. from comments.models import CommentRoot object_type = ContentType.objects.get(model="project") commentRoot = CommentRoot.objects.get_or_create(commenter=project.author, content_type=object_type, object_id=project.pk)[0] nodes = commentRoot.get_descendants(include_self=False) ## Put the comments in the comment form. Then users can only use this form to reply to comments on this project. from comments.forms import commentForm commentform = commentForm() commentform.fields['parent'].queryset = nodes c = RequestContext( request, dict(project=project, user=request.user, author=author, authorprofile=authorprofile, authorpic=authorpic, commentRootId=commentRoot.id, nodes=nodes, commentform=commentform, images=images, texts=texts, galleryname="base", mainthumb=[mainthumb], downloadurl=download.filename.url)) return render(request, "article.html", c)
def project(request, pk): ## If the post doesn't exist 404 them try: project = Project.objects.exclude(draft=True).get(pk=pk) except: raise Http404 object_type = ContentType.objects.get_for_model(project) projectfiles = fileobject.objects.filter(content_type=object_type,object_id=project.id) if project.enf_consistancy == False: raise Http404 else: mainthumb = project.thumbnail.get_thumb(650,500) images=[]# Images in the project; will be handed to template # Get readme as first item in the list of texts to hand to the template. try: #Thus is in a try statement becouse the file backend might name the readme "ReadMe_1.md" or similar. Need to switch it out for "bodyfile" forighnkey at some point. readme = project.bodyFile htmlreadme=htmlobject.objects.get_or_create(fileobject = readme )[0] texts = [[htmlreadme, path.split(str(readme.filename))[1]]] except: texts = [] pass # norenders. this is the number of files in the project not rendered. We currently do nothing.. unless someone changed that and not this note. norenders =0 for i in projectfiles: thumb=i.get_thumb(65,50) renderer=i.filetype if renderer != "norender" and renderer != "text": images.append(thumb) if renderer == "norender": norenders +=1 if renderer == "text" and i != project.bodyFile : htmlmodel=htmlobject.objects.get_or_create(fileobject = i )[0] texts.append([htmlmodel, path.split(str(i.filename))[1]]) download=zippedobject.objects.get_or_create(project=project)[0] author = project.author from userProfile.models import userProfile authorprofile = userProfile.objects.filter(user=author)[0] try: authorpic=authorprofile.userpic.get_thumb(128,128)[0] except: authorpic=False ## get the root comment of the project and use it to get all the projects comments. from comments.models import CommentRoot object_type = ContentType.objects.get(model="project") commentRoot = CommentRoot.objects.get_or_create(commenter=project.author, content_type=object_type, object_id=project.pk)[0] nodes = commentRoot.get_descendants(include_self=False) ## Put the comments in the comment form. Then users can only use this form to reply to comments on this project. from comments.forms import commentForm commentform = commentForm() commentform.fields['parent'].queryset = nodes if download.filename: downloadurl=download.filename.url else: downloadurl=None c = RequestContext(request, dict(project=project, user=request.user, author=author, authorprofile=authorprofile, authorpic=authorpic, commentRootId=commentRoot.id, nodes=nodes, commentform=commentform, moreobjects=norenders, images=images, texts=texts, galleryname="base", mainthumb=[mainthumb], downloadurl=downloadurl)) return render(request, "article.html", c)
def new_comment(request, post_id): """ Posts a new comment """ # Would use @login_required but can't handle POST request on return if not request.user.is_authenticated(): return redirect(reverse('accounts.views.login')) comment_of_interest = comment(user_id=request.user, post_id=post.objects.get(id=post_id)) form = commentForm(request.POST, instance=comment_of_interest) if request.method == "POST": # SPAM CHECK # bool_spam = spam_check(form['content'].value(), comment_of_interest, request) # if bool_spam: # return request.user.check_akismet(request) # Check for too frequent commenting (likely spam) comments_in_last_min = comment.objects.filter( time_created__gte=datetime.datetime.now() - datetime.timedelta(seconds=COMMENT_TIME_FRAME), user_id=request.user) if len(comments_in_last_min) >= 1: return render( request, 'rapid_comment.html', { 'time_frame': COMMENT_TIME_FRAME, 'redirect_to': request.GET['next'], 'content': form['content'].value() }) if form.is_valid(): temp = form.save(commit=False) parent = form['parent'].value() if parent == '': #Set a blank path then save it to get an ID temp.path = [] temp.save() temp.path = [temp.id] else: #Get the parent node node = comment.objects.get(id=parent) node.children += 1 #Keep track of children to display node.save() temp.depth = node.depth + 1 temp.path = node.path #Store parents path then apply comment ID temp.save() temp.path.append(temp.id) #Final save for parents and children temp.save() else: # Comment errors -- store in session for post_page view request.session['bad_comment_form'] = request.POST if 'next' in request.GET: return redirect(request.GET['next']) else: # Should never be entered, but remove session if so del request.session['bad_comment_form'] return redirect('/')
def index(request, video_hash, video_id): current = Video.objects.get(id=video_id) steem_url, smoke_url, whale_url, total_likes, total_dislikes, total_earning = get_post_details(current.id) current = Video.objects.get(id=video_id) hash = json.loads(current.video) resolution = [2160, 1440, 1080, 720, 480, 360, 240 , 144] isVideo = False for each_res in resolution: if str(each_res) in current.video: if hash[str(each_res)] == video_hash: isVideo = True break if isVideo == True: views = current.views current.views = views+1 current.save() featured = Video.objects.all().order_by('-id')[:1] recommend = Video.objects.all().order_by('-views')[:1] user = User.objects.get(id=current.user_id) count = Video.objects.filter(user_id=current.user_id).count() bestHash_Featured = [] bestHash_Recomended = [] for each_video in featured: for each_res in resolution: if str(each_res) in each_video.video: hash1 = demjson.decode(each_video.video) each_video.featured = hash1[str(each_res)] break for each_video in recommend: for each_res in resolution: if str(each_res) in each_video.video: hash1 = demjson.decode(each_video.video) each_video.recommend = hash1[str(each_res)] break dump = json.dumps(hash) video_content = '' for quality, this_hash in hash.items(): video_content = video_content + '{\n\t src: \'https://gateway.ipfs.io/ipfs/' + this_hash + '\',\n\t type: \'video/mp4\',\n\t size: ' + quality + ',\n},\n' try: chkLike, chkDislike = likedordisliked (request, request.user.id, video_id) except: chkLike = False chkDislike = False cmntForm = commentForm() all_comments = commentsModel.objects.filter(video = video_id) return render(request, "watch/base.html", {'video_hash': hash, 'cont': video_content, 'latest': featured, 'recommended': recommend, 'current': current, 'user': user, 'count': count, 'steem_url': steem_url, 'smoke_url': smoke_url, 'whale_url': whale_url, 'chkLike': chkLike, 'chkDislike':chkDislike, 'total_likes': total_likes, 'total_dislikes': total_dislikes, 'total_earning': total_earning, 'cmntForm':cmntForm, 'all_comments':all_comments})
def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) form = commentForm() comment_list = self.object.comment_set.all() context.update({'form': form, 'comment_list': comment_list}) return context