def movie_detail(request, pk): context = {} movie = Movie.objects.get(pk=pk) context['movie'] = movie context['imdb'] = 'http://www.imdb.com/title/' + str(movie.imdb_id) context['form1'] = CommentForm() if request.method == 'POST': form1 = CommentForm(request.POST) context['form1'] = form1 if form1.is_valid(): print 'valid form1' print request.user if request.user.is_authenticated(): print 'comment' new_comment = Comment() new_comment.is_response = False new_comment.text = form1.cleaned_data['text'] new_comment.user = request.user new_comment.movie = movie new_comment.save() return HttpResponseRedirect('/movie_detail/%s' %pk ) else: print 'anonymous user' return HttpResponseRedirect('/please_login/') else: print 'form1 not valid' else: print 'GET' return render_to_response('movie_detail.html', context, context_instance=RequestContext(request))
def test_cascade_on_delete(self): comment = Comment(recipe=self.recipe, user=User.objects.get(pk=1)) comment.save() self.recipe.delete() with self.assertRaises(ObjectDoesNotExist): Comment.objects.get(pk=1)
def create_comment(request): if all(x in request.POST for x in ['nickname', 'content', 'captcha_key', 'captcha_value']): # Human validation by captcha form captcha_key = request.POST['captcha_key'] captcha_value = request.POST['captcha_value'] try: captcha = CaptchaStore.objects.get(challenge=captcha_value, hashkey=captcha_key) captcha.delete() except: return JsonResponse({ 'state': 'fail', 'msg': 'Captcha input is not valid' }) comment = Comment(nickname=request.POST['nickname'], content=request.POST['content']) comment.save() update_firebase_database('/comment', 'last_comment_id', comment.id) return JsonResponse({ 'state': 'success', 'msg': 'Succeed to create comment', 'comment_id': comment.id }) else: return HttpResponse(status=400)
def reply_comment(request, username, slug, comment_id): authenticated_user = get_authenticated_user(request) comment = get_object_or_404(Comment, id=comment_id) # Get the Comment if request.method == 'POST': form = CommentForm(request.POST) # Get form if form.is_valid(): text = form.cleaned_data['textInput'] # Read body # Create a Comment model with form data new_comment = Comment( author=authenticated_user, text=text, ) new_comment.save() # Save it # Add new comment to comment replys comment.replys.add(new_comment) notif = Notification( receiver=comment.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> پاسخی روی <a href="/user/{username}/post/{slug}/#comment_{comment.id}">نظر</a> شما ارسال کرد', notif_type='reply') notif.save() # Redirect user to 'person:post:detail' url return HttpResponseRedirect('/user/' + username + '/post/' + slug)
def add_comment(request, username, slug): authenticated_user = get_authenticated_user(request) person = get_object_or_404(Person, username=username) # Get the Person post = get_object_or_404(Post, author=person, slug=slug) # Get the Post if request.method == 'POST': form = CommentForm(request.POST) # Get form if form.is_valid(): text = form.cleaned_data['textInput'] # Read body # Create a Comment model with form data comment = Comment( author=authenticated_user, text=text, ) comment.save() # Save it post.comments.add(comment) post.len_comments = int(post.len_comments) + 1 post.save() notif = Notification( receiver=post.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> نظری روی مطلب «<a href="/user/{username}/post/{slug}/">{post.title}</a>» شما ارسال کرد', notif_type='comment') notif.save() # Redirect user to 'person:post:detail' url return HttpResponseRedirect('/user/' + username + '/post/' + slug)
def episode_detail(request, pk): context = {} episode = Episode.objects.get(pk=pk) context['form'] = CommentForm() context['episode'] = episode context['imdb'] = 'http://www.imdb.com/title/' + str(episode.imdb_id) if request.method == 'POST': form = CommentForm(request.POST) context['form'] = form if form.is_valid(): if request.user.is_authenticated: new_comment = Comment() new_comment.text = form.cleaned_data['text'] new_comment.user = request.user new_comment.episode = episode new_comment.save() elif request.user.is_anonymous: print 'anonymous user' return HttpResponseRedirect('/please_login/') return HttpResponseRedirect('/episode_detail/%s' % pk) else: print 'form not valid' return render_to_response('episode_detail.html', context, context_instance=RequestContext(request))
def movie_detail(request, pk): context = {} movie = Movie.objects.get(pk=pk) context['movie'] = movie context['imdb'] = 'http://www.imdb.com/title/' + str(movie.imdb_id) context['form1'] = CommentForm() if request.method == 'POST': form1 = CommentForm(request.POST) context['form1'] = form1 if form1.is_valid(): print 'valid form1' print request.user if request.user.is_authenticated(): print 'comment' new_comment = Comment() new_comment.is_response = False new_comment.text = form1.cleaned_data['text'] new_comment.user = request.user new_comment.movie = movie new_comment.save() return HttpResponseRedirect('/movie_detail/%s' % pk) else: print 'anonymous user' return HttpResponseRedirect('/please_login/') else: print 'form1 not valid' else: print 'GET' return render_to_response('movie_detail.html', context, context_instance=RequestContext(request))
def show_detail(request, pk): context = {} show = Show.objects.get(pk=pk) context['form'] = CommentForm() context['show'] = show context['imdb'] = 'http://www.imdb.com/title/' + str(show.imdb_id) if request.method == 'POST': form = CommentForm(request.POST) context['form'] = form if form.is_valid(): if request.user.is_anonymous: print 'anonymous user' return HttpResponseRedirect('/please_login/') else: new_comment = Comment() new_comment.text = form.cleaned_data['text'] new_comment.user = request.user new_comment.show = show new_comment.save() return HttpResponseRedirect('/show_detail/%s' % pk) else: print 'form not valid' return render_to_response('show_detail.html', context, context_instance=RequestContext(request))
def main(request): num_visits = request.session.get('num_visits',0) request.session['num_visits'] = num_visits + 1 isUploadImg = False img = None print(request.user.username) if request.method == 'POST' and request.content_type == 'multipart/form-data': print(request.content_type) img = Img(img_url = request.FILES.get('img'), creator = request.user) img.save() isUploadImg = True img.computerScore = assessPicture(str(img.img_url)) img.save() if request.method == 'POST' and request.content_type == 'application/x-www-form-urlencoded': comment = Comment(content = request.POST.get('comment_field'), creator = request.user) comment.save() comments = Comment.objects.all().order_by('create_time') imgs = Img.objects.all().order_by('-computerScore') context = { 'imgs' : imgs, 'isUploadImg' : isUploadImg, 'currentImg' : img, 'num_visits' : num_visits, 'comments' : comments, } return render(request, 'main/index.html', context);
def replychannel(request, pk1, pk2): context = {} if request.user.is_authenticated(): print 'reply' print request.GET.get('reply') new_comment = Comment() new_comment.is_reply = True new_comment.text = request.GET.get('reply') new_comment.user = request.user new_comment.channel = Channel.objects.get(pk=pk1) new_comment.save() new_reply = Reply() new_reply.text = request.GET.get('reply') new_reply.original_response = Response.objects.get(pk=pk2) new_reply.copy = new_comment new_reply.user = request.user new_reply.channel = Channel.objects.get(pk=pk1) new_reply.save() return HttpResponseRedirect('/channel_detail/%s' % pk1) else: print 'anonymous user' return HttpResponseRedirect('/please_login/') return render_to_response('channel_detail.html', context, context_instance=RequestContext(request))
def replychannel(request, pk1, pk2): context = {} if request.user.is_authenticated(): print 'reply' print request.GET.get('reply') new_comment = Comment() new_comment.is_reply = True new_comment.text = request.GET.get('reply') new_comment.user = request.user new_comment.channel = Channel.objects.get(pk=pk1) new_comment.save() new_reply = Reply() new_reply.text = request.GET.get('reply') new_reply.original_response = Response.objects.get(pk=pk2) new_reply.copy = new_comment new_reply.user = request.user new_reply.channel = Channel.objects.get(pk=pk1) new_reply.save() return HttpResponseRedirect('/channel_detail/%s' %pk1) else: print 'anonymous user' return HttpResponseRedirect('/please_login/') return render_to_response('channel_detail.html', context, context_instance=RequestContext(request))
def on_message(self, message): comment_json = json.loads(message) form = CommentForm(data=comment_json) form.is_valid() # TODO: raise exception if not valid comment = Comment(**form.clean()) comment.save() # self.write_message(self.generate_comment_json()) self.update_waiters()
def addcoment(request, pro_id): if request.method == 'POST': c = forms.ComentForm(request.POST) coment = Comment() coment.project = Project.objects.get(id=int(pro_id)) coment.content = c.data['content'] coment.user = User.objects.get(id=1) coment.save() return redirect('/project/' + str(pro_id)) else: f = forms.ComentForm return render_to_response('comment.html', RequestContext(request, {'formset': f}))
def create(self, validated_data): parent_comment_id = validated_data['parent_comment']['id'] del validated_data['parent_comment'] post_id = validated_data['post']['id'] del validated_data['post'] comment = Comment(**validated_data) if parent_comment_id: comment.parent_comment_id = parent_comment_id if post_id: comment.post_id = post_id comment.save() return comment
def addComment(request): authorName = request.POST['author'] author = User.objects.get(username=authorName) imgID = request.POST['imgID'] currentImg = Img.objects.get(id=imgID) content = request.POST['content'] comment = Comment(id='123', author=author, img=currentImg, content=content) comment.save() context = { 'currentImg': currentImg, } return HttpResponseRedirect('/blog/' + authorName + '/' + imgID)
def post(self, request, post_title): post = Post.objects.filter(slug=post_title)[0] comment = Comment() comment.post = post comment.text = request.POST['text'] if isinstance(request.user, User): comment.author = request.user comment.save() else: form = NewCommentForm(request.POST) if form.is_valid(): comment.save() return redirect('/post/' + post.slug)
def commenting(request, post_id): if request.method == "POST": now = datetime.datetime.now() text = request.POST.get("text") post = Post.objects.get(post_id= post_id) comment = Comment(texts = text,post = post, user = request.user, pub_date = now) comment.save() post.comments = post.comments + 1 post.save() link = '//127.0.0.1:8000/main/' + str(post_id) return redirect(link)
def page(request, page_name): """Page with an article.""" grp = get_info(request) if len(page_name) > 4: if page_name[-4:] == '.xml': if len(Page.objects.filter(url=page_name[:-4])) > 0: p = Page.objects.get(url=page_name[:-4]) t = loader.get_template('main/base.xml') c = Context({ 'title': p.title, 'link': request.build_absolute_uri(reverse('pages', args=(p.url, ))), 'date': p.add_date, 'description': p.text[:100] + '...' }) return HttpResponse(t.render(c), content_type="text/xml") if request.method == 'POST': try: text = request.POST['text'] submit_date = datetime.now() user_ip = get_ip(request) pg = Page.objects.get(url=page_name) com = Comment(user=request.user, text=text, date=submit_date, ip=user_ip, page=pg) com.save() except Exception as ex: print(ex) return HttpResponseRedirect(reverse('page', args=(page_name, ))) else: pages_list = get_pages(request, '') urls = [page['url'] for page in pages_list] if page_name in urls: page = pages_list[urls.index(page_name)] else: raise Http404() comments = get_comments(request, page_name) template = loader.get_template('main/text.html') context = RequestContext(request, { 'selected_page': page, 'group': grp, 'comments': comments }) return HttpResponse(template.render(context))
def article(request, id_post): post = Post.objects.get(pk=id_post) if request.method == 'POST': content = request.POST['comment-content'] comment = Comment() comment.author = User.objects.get(pk=request.user.id) comment.post = post comment.content = content comment.approved = True comment.save() context = RequestContext(request) comments = Comment.objects.filter(post=post) context['post'] = post context['comments'] = comments return render_to_response("post.html", context)
def __init__(self, sender, post, context): """ 构造 :param sender: 发送者 pk :param post: 文章 pk :param context: 评论内容 """ # 将数据存入数据库 comment = Comment( sender=sender, post=post, is_child=False, context=context, ) comment.save()
def answering_child(request, post_id,comment_id, child_id): if request.method == "POST": text = request.POST.get("text") now = datetime.datetime.now() child = CommentChild.objects.get(child_id = child_id) post = Post.objects.get(post_id = post_id) copy_comment = Comment(texts = text, user = child.user , post = post, pub_date = now, display = False) copy_comment.save() comment2 = Comment.objects.get(texts = text, post = post, user = child.user, pub_date = now) #anscomment = CommentChild(texts = text, prev = prev, copy = copy_comment, user = request.user, comment = comment, post = post) #anscomment.save() link = '//127.0.0.1:8000/main/' + str(post_id)+'/'+str(comment_id)+'/'+str(child_id)+'/'+str(comment2.comment_id)+'/'+'really_child_answering/' return redirect(link)
def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() # Form validation if form.is_valid(): # Comment creation and completion comment = Comment() comment.body = form.cleaned_data['body'] comment.user = request.user comment.house = self.object comment.save() return self.form_valid(form) else: return self.form_invalid(form)
def commentchannel(request, pk): context = {} if request.user.is_authenticated(): print 'comment' print request.GET.get('comment') new_comment = Comment() new_comment.is_reply = False new_comment.text = request.GET.get('comment') new_comment.user = request.user new_comment.channel = Channel.objects.get(pk=pk) new_comment.save() return HttpResponseRedirect('/channel_detail/%s' %pk) else: print 'anonymous user' return HttpResponseRedirect('/please_login/') return render_to_response('channel_detail.html', context, context_instance=RequestContext(request))
def detail(request, pk): post = Post.objects.get(pk=pk) comments = Comment.objects.filter(post=post) form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post, ) comment.save() context = {"post": post, "comments": comments, "form": form} return render(request, "main/detail.html", context)
def __init__(self, sender, receiver, post, parent, context): """ 构造 :param sender: 发送者 pk :param receiver: 接收者 pk :param post: 文章 pk :param parent: 父级评论 pk :param context: 评论 """ # 将数据存入数据库 comment = Comment(sender=sender, receiver=receiver, post=post, is_child=True, parent=parent, context=context) comment.save()
def post(self, request, *args, **kwargs): author = request.POST['author'] text = request.POST['text'] parent_id = request.POST.get('parent', None) form = CommentForm({'author': author, 'text': text, 'parent': parent_id}) form.is_valid() # TODO: raise exception if invalid comment_data = form.clean() comment = Comment(**comment_data) comment.save() comment_list = self.get_comment_list() response_dict = {'comments': comment_list} return JsonResponse(response_dict, safe=False)
def post(request, postid): post = get_object_or_404(Post, id=postid) if request.method == "POST": u = UserProfile.objects.get(user__username=request.user) comment_body = request.POST.get('body') print comment_body comment = Comment(body=comment_body, author=u.user, post=post) comment.save() messages.success(request, '成功发表评论!') return HttpResponseRedirect('/post/%s' % postid) comments = [] commentObj = post.comments.order_by('timestamp') for i in commentObj: comments.append(i) return render_to_response( 'post.html', {'post': post, 'comments': comments}, context_instance=(RequestContext(request)))
def answering(request, post_id,comment_id): if request.method == "POST": now = datetime.datetime.now() text = request.POST.get("text") post = Post.objects.get(post_id = post_id) comment1 = Comment(texts = text,post = post, user = request.user, pub_date = now, display = False) comment1.save() comment2 = Comment.objects.get(texts = text,post = post, user = request.user, pub_date = now) #comment2 = Comment.objects.get(comment_id=id) #child = CommentChild(texts = text, copy =comment2, user = request.user, prev = comment, comment = comment, post = post) #child.save() link = '//127.0.0.1:8000/main/' + str(post_id)+'/'+str(comment_id)+'/'+str(comment2.comment_id )+'/' return redirect(link)
def post_comment_create(request, pid): # post is the only possible method for this view post = get_object_or_404(Post, pk=pid) if not post.is_published(): raise Http404("Associated post does not exist.") return redirect(reverse('index')) content = request.POST.get('comment') replyto = re.match(r'@\w+', content) if replyto is not None: replyto = replyto.group() # we should save raw text # content = '<a href=\"/user/'+replyto[1:]+'\" class=\"orange-text\">'+replyto+'</a>'+content[len(replyto):] c = Comment(creator=request.user, post=post, content=content) c.save() return redirect(reverse('post_view', args=[pid]))
def commentchannel(request, pk): context = {} if request.user.is_authenticated(): print 'comment' print request.GET.get('comment') new_comment = Comment() new_comment.is_reply = False new_comment.text = request.GET.get('comment') new_comment.user = request.user new_comment.channel = Channel.objects.get(pk=pk) new_comment.save() return HttpResponseRedirect('/channel_detail/%s' % pk) else: print 'anonymous user' return HttpResponseRedirect('/please_login/') return render_to_response('channel_detail.html', context, context_instance=RequestContext(request))
def post(request, postid): post = get_object_or_404(Post, id=postid) if request.method == "POST": u = UserProfile.objects.get(user__username=request.user) comment_body = request.POST.get('body') print comment_body comment = Comment(body=comment_body, author=u.user, post=post) comment.save() messages.success(request, '成功发表评论!') return HttpResponseRedirect('/post/%s' % postid) comments = [] commentObj = post.comments.order_by('timestamp') for i in commentObj: comments.append(i) return render_to_response('post.html', { 'post': post, 'comments': comments }, context_instance=(RequestContext(request)))
def post(self, *args, **kwargs): author = self.get_argument('author', None) text = self.get_argument('text', None) parent_id = self.get_argument('parentCommentId', None) form = CommentForm(data={ 'author': author, 'text': text, 'parent': parent_id }) form.is_valid() # TODO: raise exception if not valid comment = Comment(**form.clean()) comment.save() response_dict = {'comments': get_comment_list()} comment_json = json.dumps(response_dict, cls=DjangoJSONEncoder) self.write(comment_json)
def page(request, page_name): """Page with an article.""" grp = get_info(request) if len(page_name) > 4: if page_name[-4:] == '.xml': if len(Page.objects.filter(url=page_name[:-4])) > 0: p = Page.objects.get(url=page_name[:-4]) t = loader.get_template('main/base.xml') c = Context({ 'title':p.title, 'link':request.build_absolute_uri(reverse('pages', args=(p.url,))), 'date':p.add_date, 'description':p.text[:100]+'...' }) return HttpResponse(t.render(c), content_type="text/xml") if request.method == 'POST': try: text = request.POST['text'] submit_date = datetime.now() user_ip = get_ip(request) pg = Page.objects.get(url=page_name) com = Comment(user=request.user, text=text, date=submit_date, ip=user_ip, page=pg) com.save() except Exception as ex: print(ex) return HttpResponseRedirect(reverse('page', args=(page_name,))) else: pages_list = get_pages(request, '') urls = [page['url'] for page in pages_list] if page_name in urls: page = pages_list[urls.index(page_name)] else: raise Http404() comments = get_comments(request, page_name) template = loader.get_template('main/text.html') context = RequestContext(request, { 'selected_page':page, 'group':grp, 'comments':comments }) return HttpResponse(template.render(context))
def imgDetail(request, user, imgID): # 用 if post 新增comments if request.method == 'POST': authorName = request.POST['author'] author = User.objects.get(username=authorName) imgID = request.POST['img'] currentImg = Img.objects.get(id=imgID) content = request.POST['content'] commentID = time.strftime('%Y%m%d%H%M%S') + authorName comment = Comment(id=commentID, author=author, img=currentImg, content=content) comment.save() user = User.objects.get(username=user) img = Img.objects.get(id=imgID) commentList = img.comments.all() print(img.img_url.url) context = {'currentImg': img, 'commentList': commentList} return render(request, 'blog/imgDetail.html', context)
def setUpDb(request): User.objects.all().delete() Category.objects.all().delete() Product.objects.all().delete() WishList.objects.all().delete() FitList.objects.all().delete() Comment.objects.all().delete() Added.objects.all().delete() TempProduct.objects.all().delete() glasses = Category(name='glasses') hats = Category(name='hats') headphones = Category(name='headphones') glasses.save() hats.save() headphones.save() rayban = Product(category = glasses, name='rayban glasses', brand = 'rayban',url='www.rayban.com', price = 129.9, description='stylish rayban', overlay='raybanol.png', photo='rayban.jpg') nike = Product(category = glasses, name='nike glasses', brand = 'nike', url='www.nike.com', photo='nike.jpg',overlay='nikeol.png', price = 99.9, description = 'sporty nike') adidas = Product(category = hats, name='adidas cap', brand = 'adidas', url='www.adidas.com', photo='addidas.jpg', overlay='addidasol.png', price = 56.9, description ='adidas cap!', yoffset = -0.58) levis = Product(category = hats, name='levis hat', brand = 'levis', url='www.levis.com', photo='levis.jpg', overlay='levisol.png', price = 67.9, description ='levis hat!', yoffset = -0.58) beats = Product(category = headphones, name='beats headphones', brand = 'beats', url='www.beats.com', photo='beats.jpg', overlay='beatsol.png', price = 256.9, description='stylish headphones!', yoffset = -0.15) sony = Product(category = headphones, name='sony headphones', brand = 'sony', url='www.sony.com', photo='sony.jpg', overlay="sonyol.png", price = 399.9, description='high quality headphones!', yoffset = -0.15) rayban.save() nike.save() adidas.save() levis.save() beats.save() sony.save() comment = Comment(product = rayban, owner = AUser.objects.get(pk=1), time=timezone.now(), content="Very nice glasses!") comment.save() wish = WishList(owner=AUser.objects.get(pk=1), product=rayban) wish.save() fit = FitList(owner=AUser.objects.get(pk=1), product=adidas) fit.save() return HttpResponse("Success!")
def add_comment_action(item_id, user_id, comment, reply_to_user=0, reply_to_comment=0): """ """ if reply_to_user == user_id: return '不能回复自己' item_set = Item.objects.filter(pk=item_id) if len(item_set) == 0: return 'item does not exists' item = item_set[0] item.comment_count += 1 item.save() try: new_comment = Comment(comment=comment) new_comment.item_id = item_id new_comment.comment_user_id = user_id if reply_to_user > 0: new_comment.reply_to_user_id = reply_to_user new_comment.reply_to_id = reply_to_comment new_comment.save() except ValueError: return '评论失败' if reply_to_user > 0: # Add Notification if reply_to_comment == 0: return '评论失败' notification = Notification(operation='c') notification.item_id = item_id notification.user_id = reply_to_user notification.related_user_id = user_id notification.comment_id = new_comment.pk notification.save() profile = Profile.objects.get(pk=reply_to_user) profile.notification_count += 1 profile.save() return new_comment
def create_comment(request): """ User can comment to an item directly or reply to a comment. """ item_id = request.POST['item'] comment = request.POST['comment'] reply_to = request.POST['reply_to'] redirect_to = APP_URL + "comment/list_comments/" + item_id if not item_id or not comment or not item_id.isdigit(): messages.error(request, '评论失败') return redirect(redirect_to) item_id = int(item_id) item = Item.objects.get(pk=item_id) if reply_to: try: reply_to = int(reply_to) if reply_to == request.user.pk: messages.error(request, '评论失败,不能回复自己') return redirect(redirect_to) comment = Comment(comment=comment) comment.item_id = item_id comment.comment_user_id = request.user.pk comment.reply_to_id = reply_to comment.save() item.comment_count += 1 item.save() except ValueError: messages.error(request, '评论失败') return redirect(redirect_to) else: comment = Comment(comment=comment) comment.item_id = item_id comment.comment_user_id = request.user.pk comment.save() item.comment_count += 1 item.save() messages.error(request, '评论成功') return redirect(redirect_to)
def create_comment(request): if all(x in request.POST for x in ['nickname', 'content', 'captcha_key', 'captcha_value']): # Human validation by captcha form captcha_key = request.POST['captcha_key'] captcha_value = request.POST['captcha_value'] try: captcha = CaptchaStore.objects.get(challenge=captcha_value, hashkey=captcha_key) captcha.delete() except: return JsonResponse({'state': 'fail', 'msg': 'Captcha input is not valid'}) comment = Comment(nickname=request.POST['nickname'], content=request.POST['content']) comment.save() update_firebase_database('/comment', 'last_comment_id', comment.id) return JsonResponse({'state': 'success', 'msg': 'Succeed to create comment', 'comment_id': comment.id}) else: return HttpResponse(status=400)
def episode_detail(request, pk): context = {} episode = Episode.objects.get(pk=pk) context['form'] = CommentForm() context['episode'] = episode context['imdb'] = 'http://www.imdb.com/title/' + str(episode.imdb_id) if request.method == 'POST': form = CommentForm(request.POST) context['form'] = form if form.is_valid(): if request.user.is_authenticated: new_comment = Comment() new_comment.text = form.cleaned_data['text'] new_comment.user = request.user new_comment.episode = episode new_comment.save() elif request.user.is_anonymous: print 'anonymous user' return HttpResponseRedirect('/please_login/') return HttpResponseRedirect('/episode_detail/%s' %pk ) else: print 'form not valid' return render_to_response('episode_detail.html', context, context_instance=RequestContext(request))
def show_detail(request, pk): context = {} show = Show.objects.get(pk=pk) context['form'] = CommentForm() context['show'] = show context['imdb'] = 'http://www.imdb.com/title/' + str(show.imdb_id) if request.method == 'POST': form = CommentForm(request.POST) context['form'] = form if form.is_valid(): if request.user.is_anonymous: print 'anonymous user' return HttpResponseRedirect('/please_login/') else: new_comment = Comment() new_comment.text = form.cleaned_data['text'] new_comment.user = request.user new_comment.show = show new_comment.save() return HttpResponseRedirect('/show_detail/%s' %pk ) else: print 'form not valid' return render_to_response('show_detail.html', context, context_instance=RequestContext(request))
def create(self, validated_data): comment = Comment(**validated_data) comment.save() return comment
def test_created_on(self): comment = Comment(recipe=self.recipe, user=User.objects.get(pk=1)) comment.save() self.assertEqual(comment.created_on.replace(second=0, microsecond=0), timezone.now().replace(second=0, microsecond=0))
def test_default_values(self): comment = Comment(recipe=self.recipe, user=User.objects.get(pk=1)) comment.save() self.assertFalse(comment.active)
def post_detail(request, username, post_id): authenticated_user = get_authenticated_user(request) person = Person.objects.get(username=username) # Get the Person post = get_object_or_404(Post, author=person, id=post_id) # Get the Post comments = Comment.objects.filter(place=post).order_by( 'id') # Get the Comments len_comments = len(comments) # Get length of comments post.views = int(post.views) + 1 post.save() if authenticated_user is not None: authenticated_user.viewed_posts.add(post) authenticated_user.save() # For comment # If form method == POST if request.method == 'POST': form = CommentForm(request.POST) # Get form if form.is_valid(): mode = form.cleaned_data['mode'] # Read mode text = form.cleaned_data['text'] # Read body text = text.replace('<', '<').replace('>', '>').replace( '\n', '<br/>') # Clean the body and recognize line breaks # If mode == comment if mode == 'comment': # Create a Comment model with form data comment = Comment(place=post, author=authenticated_user, text=text) comment.save() # Save it post.comments = int(post.comments) + 1 post.save() notif = Notification( givver=post.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> نظری روی مطلب «<a href="/user/{post.author.username}/post/{post.id}/">{post.title}</a>» شما ارسال کرد', notif_type='comment') notif.save() else: replay = Comment(author=authenticated_user, text=text) replay.save() comment = Comment.objects.get(id=mode) comment.replays.add(replay) comment.save() post.comments = int(post.comments) + 1 post.save() notif = Notification( givver=comment.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> پاسخی به <a href="/user/{post.author.username}/post/{post.id}/#comments">نظر</a> شما داد', notif_type='replay') notif.save() notif2 = Notification( givver=post.author, message= f'<a href="/user/{authenticated_user.username}/">{authenticated_user.name}</a> نظری روی مطلب «<a href="/user/{post.author.username}/post/{post.id}/">{post.title}</a>» شما ارسال کرد', notif_type='comment') notif2.save() return HttpResponseRedirect('/user/' + post.author.username + '/post/' + str(post.id)) # If form method == GET else: form = CommentForm() # Give form to user context = { 'authenticated_user': authenticated_user, 'new_notifications': get_new_notifications(authenticated_user), 'post': post, 'post_body': translate_to_html(post.body), 'comments': comments, 'len_comments': len_comments, 'form': form, 'ads_list': ads_list(), 'current_url': str(request.path).replace('/', '%2F'), } return render(request, 'post/detail.html', context)
def create(self, validated_data): comment = Comment(**validated_data) comment.author = User.objects.first() comment.created = datetime.datetime.now() comment.save() return comment