def dispatch(self, request, *args, **kwargs): #@todo: Sprawdzic, czy uzytkownik moze komentowac meta = UserMetaData.objects.get( user = request.user ) if request.POST and meta.canComment: form = CommentForm( request.POST ) if form.is_valid(): obj = form.save( commit = False ) if obj.text.strip() == "": return HttpResponse( 0 ) obj.author = request.user obj.date = datetime.now() obj.save() else: return HttpResponse( 0 ) form = CommentForm( initial={"content" : Content.objects.get( id = kwargs["id"] ) }) comments = Comment.objects.filter( content = Content.objects.get( id = kwargs["id"] ) ) data = { "MEDIA_URL": MEDIA_URL, "user" : request.user, "comments" : comments, "form" : form, "id" : kwargs["id"] } data.update( csrf( request ) ) return render_to_response( "core/comments.html", data )
def comment_block (request, object): """ Returns the info needed to be used with the comments template Params: request: The request instance object: The object to comment on (for instance an Event) """ if 'new_comment' in request.POST: comment_form = CommentForm(object, request.POST) if comment_form.is_valid(): comment = comment_form.save(commit = False) comment.user = request.user comment.save() comment_form = CommentForm(object) request.message_success(_("Comment added successfully!")) else: comment_form = CommentForm(object) try: object.comments except: raise IntegrityError("Models using comments should have a generic relation named 'comments' to the Comment model!") return {'form': comment_form, 'list': object.comments.all()}
def serve(self, request): from core.forms import CommentForm if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): if request.user.is_authenticated(): inst = form.save(commit=False) inst.user = request.user inst.save() messages.info(request, 'Сообщенее добавлено.Оно будет доступно для всеобщего обозрения после проверки администратором.') else: messages.error(request, 'Коментарии только для авторизированых пользователей.') # send message return render(request, self.template, { 'self': self, 'form': form, }) else: form = CommentForm() return render(request, self.template, { 'self': self, 'form': form, })
def article_detail( request, pk, template_name='accounts/articles_related/article_details.html'): article = get_object_or_404(Article, pk=pk) # article = Article.objects.get(pk=pk) comments = Comment.objects.filter(article=article, reply=None).order_by('-id') if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(article=article, user=request.user, content=content, reply=comment_qs) comment.save() return redirect('my_articles') comment_form = CommentForm() context = { 'object': article, 'comments': comments, 'comment_form': comment_form } return render(request, template_name, context)
def show_comments(context): from core.models import Comment, Profile, Event from datetime import datetime comments = Comment.objects.filter(event__pk=context['event'].id).prefetch_related('user') from core.forms import CommentForm data = {"event": context['event'].id, "user": context['request'].user, "timestamp": datetime.now()} form = CommentForm(initial=data) form.user = context['request'].user form.event = context['event'].id print "DEBUG FORM" print form.event, form.user, form #prepoulate the form here - user = request.user, timestamp = now() #event = event_pk print "DEBUG COMMENETS TAG" for comment in comments: print comment.comment, comment.user, comment.timestamp final_comments = [] for comment in comments: profile = Profile.objects.get(user=comment.user) temp_comment = {"comment": comment.comment, "user": comment.user, "picture": profile.picture, "timestamp": comment.timestamp, } final_comments.append(temp_comment) return {"comments": final_comments, "form": form}
def test_comment_valid(self): """test_comment_form_validation() checks form with is_valid() method.""" form = CommentForm(data={ 'name': 'Tester', 'email': '*****@*****.**', 'body': 'testoo' }) self.assertTrue(form.is_valid())
def comment_submit(id): form = CommentForm() if form.validate_on_submit(): db.session.add(Comments(datetime.datetime.now(), id, current_user.id, form.comment.data)) book = Books.query.filter_by(id=id).first() book.comment_count += 1 db.session.commit() return redirect(url_for("books.books_comment", id=id))
def post(self, request): # pass filled out HTML-Form from View to CommentForm() form = CommentForm(request.POST) if form.is_valid(): # create a Comment DB Entry text = form.cleaned_data['text'] video_id = request.POST['video'] video = Video.objects.get(id=video_id) new_comment = Comment(text=text, user=request.user, video=video) new_comment.save() return HttpResponseRedirect('/video/{}'.format(str(video_id))) return HttpResponse('This is Register view. POST Request.')
def comment_block(request, object): """ Returns the info needed to be used with the comments template Params: request: The request instance object: The object to comment on (for instance an Event) """ if 'new_comment' in request.POST: comment_form = CommentForm(object, request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = request.user comment.save() comment_form = CommentForm(object) request.message_success(_("Comment added successfully!")) else: comment_form = CommentForm(object) try: object.comments except: raise IntegrityError( "Models using comments should have a generic relation named 'comments' to the Comment model!" ) return {'form': comment_form, 'list': object.comments.all()}
def new_comment(request, post_id): post = Post.objects.get(id=post_id) if post is None: raise Http404('No task matches the given query.') form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.commenter = request.user comment.save() else: messages.error(request, 'We had a problem saving your comment.') return redirect('comments', post_id=post_id)
def get(self, request, id): # fetch video from DB by ID video_by_id = Video.objects.get(id=id) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) video_by_id.path = 'http://localhost:5000/get_video/' + video_by_id.path print(video_by_id) print(video_by_id.path) context = {'video': video_by_id} if request.user.is_authenticated: print('user signed in') comment_form = CommentForm() context['form'] = comment_form comments = Comment.objects.filter( video__id=id).order_by('-datetime')[:5] print(comments) context['comments'] = comments try: channel = Channel.objects.filter( user__username=request.user).get().channel_name != "" print(channel) context['channel'] = channel except Channel.DoesNotExist: channel = False return render(request, self.template_name, context)
def add_comment(request, pk): """Add a new comment.""" p = request.POST if p.has_key("body") and p["body"]: author = "Anonymous" if p["author"]: author = p["author"] comment = Comment(post=Post.objects.get(pk=pk)) cf = CommentForm(p, instance=comment) cf.fields["author"].required = False comment = cf.save(commit=False) comment.author = author comment.save() return HttpResponseRedirect(reverse("core.views.post", args=[pk]))
def view_post(request, pk): post = get_object_or_404(Post, pk=pk) form = CommentForm(request.POST or None) recommend_post_form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.publisher = request.user comment.post = post comment.save() return redirect(request.path) form.initial['publisher'] = request.user.pk return render_to_response('core/post_detail.html', { 'post': post, 'form': form, }, context_instance=RequestContext(request))
def add_comment(request: WSGIRequest, post_pk: str) -> HttpResponseRedirect: comment_form = CommentForm(request.POST) post = Post.objects.get(pk=post_pk) year_month_slug = (post.year, post.month, post.slug) if comment_form.is_valid(): comment = Comment.objects.create( content=comment_form.cleaned_data['content'], commenter=request.user, post_id=post_pk, parent_id=request.POST.get('parent') ) fragment_identifier = "#comment-{}".format(comment.pk) return redirect( reverse("show_post", args=year_month_slug) + fragment_identifier ) else: messages.warning(request, "Comments may not be blank.") return redirect('show_post', *year_month_slug)
def sendcomment(request): user = request.user form = CommentForm(request.POST) if form.is_valid(): data = form.cleaned_data classname = data['objectclass'] objclass = { 'Mix': Mix, 'Group': Group, 'Tag': Tag, 'Platform': Platform }[classname] obj = objclass.objects.get(id=data['objectid']) comment = Comment(content_object=obj, text=data['text'], user=user) comment.save() return HttpResponseRedirect(comment.get_absolute_url()) else: #2do error message return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def details(request, project_id, message_id): t = 'projects/message/details.html' response_vars = { } project = Project.objects.get(id=project_id) message = Message.objects.get(id=message_id) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): message.comments.create(comment = comment_form.cleaned_data["comment"], user=request.user) return HttpResponseRedirect(reverse('projects.views.message.details', args=[unicode(project.id), message_id])) else: comment_form = CommentForm() response_vars['message'] = message response_vars['comment_form'] = comment_form response_vars['comments'] = message.comments.all().order_by("-created") return render_project(request, project_id, t, response_vars)
def post(self, request, *args, **kwargs): print(request.POST) # create a form instance and populate it with data from the request: form = CommentForm(request.POST, auto_id=True) # check whether it's valid: if form.is_valid(): form.instance.user = request.user form.instance.issue = Issue.objects.get(pk=self.kwargs['pk']) form.save() return redirect( reverse('project:repository:issue:overview', kwargs={ 'project_title': kwargs['project_title'], 'repository_title': kwargs['repository_title'], 'pk': kwargs['pk'] } ) ) else: return HttpResponseBadRequest
def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create comment object but don't save database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render( request, "core/post_detail.html", { "post": post, "comments": comments, "new_comment": new_comment, "comment_form": comment_form })
def comments(request, post_id): """View function for home page of site.""" comments = Comment.objects.filter(post__id=post_id) post = Post.objects.get(id=post_id) form = CommentForm() # Render the HTML template index.html with the data in the context variable response = render( request, 'core/comment.html', { "comments": comments, "post_id": post_id, "post": post, "comment_form": form }) return response
def Detail(request, pk): post = Post.objects.get(pk=pk) comments = Comment.objects.filter(post=post) form = CommentForm() context = { 'post': post, 'comments': comments, 'form': form, } if request.is_ajax() and request.POST: text = request.POST.get('comment') comment = Comment(text=text, post=post) comment.save() data = {'message': request.POST.get('comment')} return HttpResponse(json.dumps(data), content_type='application/json') return render(request, 'core/detail.html', context)
def get_context_data(self, *args, **kwargs): context_data = super(IssueDetailView, self).get_context_data(*args, **kwargs) context_data.update({ 'comment_form': CommentForm(), 'user_proposals': self.object.user_documents(self.request.user) }) context_data["delegation"] = self.object.get_delegation( self.request.user) context_data["polities"] = list( set([t.polity for t in self.object.topics.all()])) # HACK! As it happens, there is only one polity... for now if not settings.FRONT_POLITY: raise NotImplementedError('NEED TO IMPLEMENT!') context_data["polity"] = context_data['polities'][0] return context_data
def comment(request, slug): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = Post.objects.get(slug=slug) comment.save() return redirect('post_detail', slug=slug) else: form = CommentForm() return render(request, 'comment_new.html', {'form': form})
def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) return render(request, 'core/comment_form.html', context={'form': form})
def new_comment(request, slug): post = get_object_or_404(UserPost, slug=slug) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.save() # Django Tutorial https://tutorial.djangogirls.org/en/django_templates/ post.comments.add(comment) return redirect('post_detail', slug=slug) else: form = CommentForm() return render(request, 'add_comment.html', {'form': form})
def create_comment(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.posted_by = request.user comment.save() return redirect(post.get_absolute_url()) else: form = CommentForm() template = 'core/add_comment.html' context = {'form': form} return render(request, template, context)
def add_comment_to_post(request, pk): cats = Category.objects.all() post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('core:post', pk=post.pk) else: form = CommentForm() return render(request, 'core/commentpost.html', { 'form': form, 'cats': cats })
def post_detail(request, post_id): post = Post.objects.get(pk=post_id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid: comment = form.save(commit=False) comment.author = request.user comment.post = post comment.pk = comment.id comment.save() return redirect('post_detail', post_id=post.pk) else: form = CommentForm() return render(request,'posts/post_detail.html', { 'post': post, 'form': CommentForm(), 'comments': post.comments.all(), })
def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) comments = post.comments.filter(active=True) new_comment = None # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude( id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by( '-same_tags', '-publish')[:4] if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render( request, 'blog/post_detail.html', { 'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts })
def test_comment_form_field_text_input(self): form = CommentForm(initial={'body': 'Test test test.'}) self.assertEqual(form['body'].value(), 'Test test test.')
def test_comment_form_field_email_input(self): form = CommentForm(initial={'email': '*****@*****.**'}) self.assertEqual(form['email'].value(), '*****@*****.**')
def test_comment_form_field_name_input(self): form = CommentForm(initial={'name': 'Tester'}) self.assertEqual(form['name'].value(), 'Tester')
def test_form_renders_item_input(self): """test_form_renders() tests input attributes render by HTML.""" form = CommentForm() # test Bootstrap CSS classes self.assertIn('class="form-control"', form.as_p())
def test_comment_invalid(self): """test_comment_form_validation() checks form with is_valid() method.""" form = CommentForm(data={'name': '', 'email': '', 'body': 'testoo'}) self.assertFalse(form.is_valid())