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 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 post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.page = self.page comment.save() return HttpResponseRedirect(self.request.path_info)
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 index(request): if request.method == 'GET': form = CommentForm() images = Image.objects.all().order_by('-id')[:3] comments = Comment.objects.all() return render(request, 'index.html', { 'images': images, 'comments': comments, 'form': form }) else: form = CommentForm(request.POST) form.instance.username = request.user.username form.instance.photo_id = request.POST['txt'] if form.is_valid(): form.save() return redirect('/') else: return HttpResponse(form )
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 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 film(request, pk): film = get_object_or_404(Film, id=pk) form = CommentForm(request.POST or None) if form.is_valid(): form.instance.user = request.user form.instance.film = film form.save() return redirect(film) return render(request, 'main/film.html', {'film': film, "form": form})
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 recipe_detail(request, pk): context = {} recipe = Recipe.objects.get(pk=pk) # Tabulate basic nutrition info tab = tabulate_basic_nutr(recipe) # Account for servings per recipe; round numbers; calc total mass sca = scale_basic_nutr(tab[0], tab[1], tab[2], tab[3], tab[4]) # Save the total number of calories per serving to the database recipe.calories_tot = sca[2]['energy_tot'] recipe.save() # Authenticate the user active = request.user.is_authenticated() # # Handle Comments old_comments = get_old_comments(recipe) if active: cntxt_comments_v = CommentForm(initial={'recipe': pk}) if request.method == 'POST': from_form = CommentForm(request.POST) if from_form.is_valid(): get_new_comments(from_form, request, old_comments, pk) return HttpResponseRedirect('/recipe_detail/%s/' % pk) # Context Variables context['recipe'] = recipe context['nutr_basic'] = sca[0] context['nutr_other'] = sca[1] context['energy_basic'] = sca[2] context['mass_basic'] = sca[3] context['nutr_individ'] = json.dumps(sca[4]) # print "%s" % json.dumps(sca[4]) context['text_dict'] = json.dumps(sca[4]) context['active'] = active context['rating_v'] = get_ratings(active, request, pk, recipe) context['rating_stat_v'] = get_rating_stats(recipe) context['old_comments_v'] = old_comments context['comments_v'] = cntxt_comments_v # Send data to template ----------------------------------------- return render_to_response('recipe_detail.html', context, context_instance=RequestContext(request))
def add_comment_test_session(request, test_session_id): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): test_session = TestSession.objects.get(id=test_session_id) comment_text = form.cleaned_data['comment_body'] comment = Comment.objects.create( comment_body=comment_text, commenter=request.user, modified_date=datetime.datetime.now()) comment.test_session.add(test_session) comment.save() return redirect('view_test_session', test_session_id)
def add_comment_defect(request, defect_id): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): defect = Defect.objects.get(id=defect_id) comment_text = form.cleaned_data['comment_body'] comment = Comment.objects.create( comment_body=comment_text, commenter=request.user, modified_date=datetime.datetime.now()) comment.defect.add(defect) comment.save() return redirect('defect_by_id', defect_id)
def mkcomment(request, pk, parent_comment=None): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] board = Board.objects.get(pk=pk) if parent_comment == None: comment = Comment.objects.create(user=request.user, board=board, text=text) else: comment = Comment.objects.create(user=request.user, board=board, text=text, parent_comment=Comment.objects.get(pk=parent_comment)) else: print "ERROR :::: "+str(form.errors) else: print "ERROR :::: HAHA LOLOLOLOLOL!!!!!!!" return HttpResponseRedirect('/board/'+pk)
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 post_comment(request): if request.POST and request.is_ajax(): json_context = {'success': False, 'form_errors': []} form = CommentForm(request.POST) comment = form.save() if form.is_valid(): json_context['success'] = 'Комментарий успешно добавлен!' json_context['commentHtml'] = render_to_string( 'comments/post_comments.html', { 'nodes': [comment], 'can_post': True }) else: json_context['form_errors'] = form.errors return HttpResponse(json.dumps(json_context), content_type="application/json") return HttpResponseForbidden()
def index_2(request, pk): new = get_object_or_404(Posts, id=pk) comment = Comments.objects.filter(post=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.post = new form.save() return redirect(index_2, pk) else: form = CommentForm() return render(request, 'main/index_2.html', { 'new': new, 'comment': comment, 'form': form })
def post_details(request, post_list_id): try: latest_post = Post.objects.get(id=post_list_id) except Post.DoesNotExist: raise Http404("Post not found") if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('/blog/'+str(post_list_id)+'/') else: form = CommentForm() context = { 'latest_post': latest_post, 'comments': latest_post.comments.all(), 'form': form } return render(request, 'main/detail.html', context)
def add_comment(request, blog_id): form = CommentForm(request.POST) article = get_object_or_404(Blog, id=blog_id) if form.is_valid(): comment = BlogComment() comment.path = [] comment.article_id = article comment.author_id = auth.get_user(request) comment.content = form.cleaned_data['comment_area'] comment.save() try: comment.path.extend(BlogComment.objects.get(id=form.cleaned_data['parent_comment']).path) comment.path.append(comment.id) except ObjectDoesNotExist: comment.path.append(comment.id) comment.save() return HttpResponse("!")
def post_detail(request, pk): template_name = 'post-detail.html' post = get_object_or_404(Post, pk=pk) image = post.get_image images = post.images.exclude(id=image.id) 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 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, template_name, locals())
def test_create_comment(django_user_model): user = django_user_model.objects.create(username='******') user.set_password('takeajacket') user.save() cult = Cult.objects.create( name='Sweet Dreams', slug='sweet-dreams', doctrine='Hold your head up, keep your head up!', city='Amsterdam', ) event = Event.objects.create( cult=cult, title='SpaceX Falcon Heavy launch', slug='falcon-heavy-launch', details='Mars! Incoming!', date='2118-02-02', time='18:00', venue='SpaceX Fans HQ', address='2314 Olympus Str, 553 77', maps_url='https://goo.gl/maps/sample-link', ) Membership.objects.create( cult=cult, user=user, role=Membership.LEADER, ) form_data = { 'body': 'Elon for president!', } form = CommentForm(data=form_data) assert form.is_valid() c = Client() logged_in = c.login(username='******', password='******') response = c.post('/' + cult.slug + '/' + event.slug + '/comment/', form_data) assert logged_in assert response.status_code == 302 assert Comment.objects.first() assert Comment.objects.first().body == form_data['body'] assert Comment.objects.first().author == user assert Comment.objects.first().event == event
def mkcomment(request, pk, parent_comment=None): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] board = Board.objects.get(pk=pk) if parent_comment == None: comment = Comment.objects.create(user=request.user, board=board, text=text) else: comment = Comment.objects.create( user=request.user, board=board, text=text, parent_comment=Comment.objects.get(pk=parent_comment)) else: print "ERROR :::: " + str(form.errors) else: print "ERROR :::: HAHA LOLOLOLOLOL!!!!!!!" return HttpResponseRedirect('/board/' + pk)
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 RecipeDetailView(request, pk): context = {} recipe = Recipe.objects.get(pk=pk) context['recipe_v'] = recipe active = request.user.is_authenticated() context['active'] = active # Get vote_state ------------------------------------------------ if active: h_temp = "_".join([str(pk), str(request.user.username)]) vote, created = Vote.objects.get_or_create(recipe=recipe, handle=h_temp) if created: return HttpResponseRedirect('/vote_stats_func/%s' % pk) context['vote_v'] = vote else: context['vote_v'] = 2 # Get vote stats ------------------------------------------------ vote_stat, created = VoteStat.objects.get_or_create(recipe=recipe) context['vote_stat_v'] = vote_stat # Retrieve old comments ----------------------------------------- old_comments = Comment.objects.filter(recipe=recipe) context['old_comments_v'] = old_comments # Show empty form for new comments, process new comments -------- if active: context['comments_v'] = CommentForm(initial={'recipe': pk}) if request.method == 'POST': from_form = CommentForm(request.POST) if from_form.is_valid(): new_comment = from_form.save() user_name = request.user.username time = str(new_comment.time_stamp) # Because comments might get moderated, a given comment-number # might not match the total number of allowed comments # preceding it (ie, if there are 10 comments, the next comment # will be #11 [ie, 10 + 1] but if #2 is deleted by the admin, # the subsequent comment should be #12 even though there are # only 11 comments in the list. length = len(old_comments) if length == 1: number = length else: number = old_comments[length - 2].number + 1 new_comment.user_name = user_name new_comment.handle = "_".join([str(pk), user_name, time]) new_comment.number = number new_comment.email = request.user.email new_comment.save() return HttpResponseRedirect('/recipe_detail/%s/' % pk) else: context['errors'] = new_comment.errors # Send data to template ----------------------------------------- return render_to_response('recipe_detail.html', context, context_instance=RequestContext(request))
def blog_detail(request, year, month, day, post): """ Get specific post using slug. """ # Issue: adding 'day' value when getting post makes post not found. post = get_object_or_404(Post, slug=post, # status='published', publish__year=year, publish__month=month,) # display a few other posts # select randomly. other_posts = Post.objects.exclude(pk=post.pk).order_by('?')[:2] comment_form = CommentForm() if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): name = comment_form.cleaned_data['name'] sender = comment_form.cleaned_data['email'] message = comment_form.cleaned_data['message'] # create instance in database. Comment.objects.create( name=name, email=sender, message=message, post=post, ) receivers = [seckeys.EMAIL_NOTIFICATION] if comment_form.cleaned_data['copy_sent']: receivers.append(sender) # send email. email_message = f"Hi, thank your for your comment, here is a copy of it: \n\n=====\n" \ f"{message}\n=====\n\n** This email is not monitored for responses." send_mail(f'Comment by {name} - kyleclarkson.ca', email_message, seckeys.EMAIL_HOST_USER, receivers) messages.add_message(request, messages.SUCCESS, 'Thank you for your email!', extra_tags='bg-success text-white') # clear form comment_form = CommentForm() context = { 'post': post, 'comment_form': comment_form, 'other_posts': other_posts, } return render(request, 'blog/blog_detail.html', context)