示例#1
0
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)
示例#2
0
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);
示例#3
0
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)
示例#4
0
文件: test_models.py 项目: wroku/mc
    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)
示例#5
0
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)
示例#6
0
def presentation(request, key):
	"""Show the presentation page with info, mini preview, comments and other options """

	# search the presentation based on its key
	p = Presentation.objects.filter(key=key).first()

	# if presentation exists
	if p is not None:
		if p.is_private:
			uspr = UserPresentation()
			if not uspr.is_allowed(request.user.id, p.id):
				raise Http404

		rename_form = RenameForm({"name":p.name})
		modify_description_form = ModifyDescriptionForm({"description":p.description})

		# Load comments from presentation's ID
		from main.models import Comment
		c = Comment()
		comments = c.get_from_presentation(p.id)

		# generate comment form
		comment_form = CommentForm()

		# generate share form
 		uspr = UserPresentation()
 		share_formset = uspr.load_share_form(p.id, request.user.id)

		# set permissions
		is_owner = False
		can_edit = False

		# check if the user is logged
		if request.user.username:
			# check if the user is the owner of the presentation
			if UserPresentation.objects.filter(user_id=request.user.id, presentation_id=p.id, is_owner=True).exists():
				is_owner = True
			# check if the user can edit the presentation
			if UserPresentation.objects.filter(user_id=request.user.id, presentation_id=p.id, can_edit=True).exists():
				can_edit = True

		# show the presentation page
		return render_to_response("presentation.html", {
			"presentation": p,
			"rename_form": rename_form,
			"modify_description_form": modify_description_form,
			"share_formset": share_formset,
			"comment_form": comment_form,
			"comments": comments,
			"view_url": request.get_host() + reverse("main.views.presentations.view", args=[key]),
			"is_owner": is_owner,
			"can_edit": can_edit,
			}, context_instance=RequestContext(request))
	else:
		# show error 404 page
		raise Http404
示例#7
0
    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()
示例#8
0
文件: comments.py 项目: swordwj/weigo
def addComment(postid, host):
    if session.get('username') != host:
        return render_template('notlogin.html')

    else:
        # 查询登录用户的ID
        sql = 'SELECT * FROM users WHERE user_name = %s;'
        parm = (host, )
        rows = User().get_User(sql, parm)
        hostid = rows[0]
        hostname = rows[1]

        if request.form['commbox'] == '':
            error = 'You left nothing!'
            # 发送内容如果为空,提示并返回主页
            sql = 'SELECT * FROM comment WHERE message_id = %s ORDER BY comment_id DESC;'
            parm = (postid, )
            comms = Comment().get_AllComment(sql, parm)
            # 显示post
            sql1 = 'SELECT * FROM message WHERE message_id = %s;'
            parm1 = (postid, )
            rows = Post().get_Post(sql1, parm1)
            post = rows[1]
            # 获取posthost和posttime
            posthostid = rows[6]
            sql2 = 'SELECT * FROM users WHERE user_id = %s;'
            parm2 = (posthostid, )
            row = User().get_User(sql2, parm2)
            posthost = row[1]
            posttime = rows[2]
            return render_template('comments.html',
                                   postid=postid,
                                   posttime=posttime,
                                   posthost=posthost,
                                   host=host,
                                   error=error,
                                   post=post,
                                   comms=comms)
        else:
            # 添加评论
            sql_add = 'INSERT INTO comment (comment_info,comment_time,message_id,user_id,comm_commnum,comm_likenum,user_name) VALUES (%s,%s,%s,%s,0,0,%s);'

            # 获取当前时间
            import datetime
            now = datetime.datetime.now()
            # 转换为指定的格式
            otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")

            parm_add = (request.form['commbox'], otherStyleTime, postid,
                        hostid, hostname)
            Comment().set_Comment(sql_add, parm_add)
            return redirect(url_for('comment', postid=postid, host=host))
示例#9
0
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)
示例#10
0
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)
示例#11
0
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))
示例#12
0
文件: views.py 项目: Lootgvfr/lotr
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))
示例#13
0
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))
示例#14
0
 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()
示例#15
0
def comment(postid, host):
    try:
        if session.get('username') != host:
            return render_template('notlogin.html')
        else:
            try:
                # 获取post内容,在评论页面显示
                sql1 = 'SELECT * FROM message WHERE message_id = %s;'
                parm1 = (postid, )
                rows = Post().get_Post(sql1, parm1)
                post = rows[1]
                posttime = rows[2]
                # 获取发post的用户信息,传递给页面
                posthostid = rows[6]
                sql2 = 'SELECT * FROM users WHERE user_id = %s;'
                parm2 = (posthostid, )
                row = User().get_User(sql2, parm2)
                posthost = row[1]
                posthostpic = row[6]
                # 获取post的所有评论,把信息返回给评论页面
                sql2 = 'SELECT comment.*,users.userpic FROM comment,users WHERE message_id = %s AND users.user_id = comment.user_id ORDER BY comment_id DESC;;'
                parm2 = (postid, )
                comms = Comment().get_AllComment(sql2, parm2)
                # 查询post的评论数量
                sql3 = 'SELECT COUNT(user_id) FROM comment WHERE message_id = %s;'
                parm3 = (postid, )
                commnum = Comment().get_Comment(sql3, parm3)
                # 更新到数据库
                sql4 = 'UPDATE message SET message_commentnum = %s  WHERE message_id = %s;'
                parm4 = (commnum[0], postid)
                Post().set_Post(sql4, parm4)
            except:
                conn = connect_db()
                conn.rollback()
                conn.close()
                traceback.print_exc()
                return render_template('error1.html')
            return render_template('comments.html',
                                   postid=postid,
                                   host=host,
                                   post=post,
                                   posthost=posthost,
                                   posthostpic=posthostpic,
                                   posttime=posttime,
                                   comms=comms)
    except:
        traceback.print_exc()
        return render_template('error.html')
示例#16
0
文件: views.py 项目: lip365/ebagu0.2
def post_comment(request):
    if not request.user.is_authenticated():
        return JsonResponse(
            {'msg': "You need to log in to post new comments."})

    parent_type = request.POST.get('parentType', None)
    parent_id = request.POST.get('parentId', None)
    raw_comment = request.POST.get('commentContent', None)

    if not all([parent_id, parent_type]) or \
      parent_type not in ['comment', 'submission'] or \
     not parent_id.isdigit():
        return HttpResponseBadRequest()

    if not raw_comment:
        return JsonResponse({'msg': "You have to write something."})
    author = User.objects.get(user=request.user)
    parent_object = None
    try:  # try and get comment or submission we're voting on
        if parent_type == 'comment':
            parent_object = Comment.objects.get(id=parent_id)
        elif parent_type == 'submission':
            parent_object = Submission.objects.get(id=parent_id)

    except (Comment.DoesNotExist, Submission.DoesNotExist):
        return HttpResponseBadRequest()

    comment = Comment.create(author=author,
                             raw_comment=raw_comment,
                             parent=parent_object)

    comment.save()
    return JsonResponse({'msg': "Your comment has been posted."})
示例#17
0
def deletePostlist(postid, host):

    try:
        if session.get('username') != host:
            return render_template('notlogin.html')
        else:
            try:
                #delete post
                sql_del = 'DELETE FROM message WHERE message_id = %s;'
                parm_del = (postid, )
                Post().set_Post(sql_del, parm_del)
                #udate the number of post
                sql_update = 'UPDATE users SET postnum = postnum - 1  WHERE user_name = %s;'
                parm = (host, )
                User().set_User(sql_update, parm)
                #delete the like of post
                sql_del1 = 'DELETE FROM likes WHERE message_id = %s;'
                parm_del1 = (postid, )
                Like().del_Like(sql_del1, parm_del1)
                #delete comments of post
                sql_del2 = 'DELETE FROM comment WHERE message_id = %s;'
                parm_del2 = (postid, )
                Comment().set_Comment(sql_del2, parm_del2)
            except:
                conn = connect_db()
                conn.rollback()
                conn.close()
                traceback.print_exc()
                return render_template('error1.html')
            return redirect(url_for('postlist', host=host))
    except:
        traceback.print_exc()
        return render_template('error.html')
示例#18
0
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)
示例#19
0
    def handle(self, *args, **options):
        # Create Faker instance
        faker = Faker()

        # Generate categories
        Category.objects.create(name='Web development')
        Category.objects.create(name='Databases')
        Category.objects.create(name='Data science')
        Category.objects.create(name='Security')
        Category.objects.create(name='Django')
        Category.objects.create(name='Python')

        # Generate 500 blog entries
        for _ in range(0, 500):
            Blog.objects.create(title=faker.sentence(), body=faker.paragraph())

        # Generate 3 comments per blog entry
        for blog in Blog.objects.iterator():
            # Create the comment objects
            comments = [
                Comment(text=faker.paragraph(), blog=blog)
                for _ in range(0, 3)
            ]

            # Builk create previous comments in the db
            Comment.objects.bulk_create(comments)
示例#20
0
    def setUp(self):
###### create Users #######
        users = ['UserA', 'UserB', 'UserC', 'UserD']
        for i in range(4):
            newUser = AUser(password='', last_login=timezone.now(), is_superuser=True, username=users[i], first_name='Firstname', last_name='Lastname', email='*****@*****.**', is_staff=True, is_active=True, date_joined=timezone.now())
            newUser.save()
            testDBModel.testUsers.append(newUser)
            testDBModel.testUsersID.append(newUser.pk)
######  add Category ######
        category1 = Category(name="hats")
        testDBModel.testCategory.append(category1)
        category1.save()


######   add product ######
        addProducts = ["ProductA", "ProductB", "ProductC", "ProductD"]
        for i in range(4):  # # add products
            newOne = Product(category=category1, name=addProducts[i], brand='brand', url='url', photo='photo', price=1.0, description='')
            newOne.save()
            testDBModel.testProducts.append(newOne)

##### ## add comments   ######
        for i in range(4):
            newOne = Comment(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i], content="null", time = timezone.now())
            newOne.save()
            testDBModel.testComments.append(newOne)

# add to wishlist first
        for i in range(4):
            newOne = WishList(product=testDBModel.testProducts[i], owner=testDBModel.testUsers[i])
            newOne.save()
示例#21
0
 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)
示例#22
0
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)
示例#23
0
 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()
示例#24
0
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))
示例#25
0
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))
示例#26
0
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))
示例#27
0
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))
示例#28
0
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)))
示例#29
0
文件: views.py 项目: orestv/ReactTest
    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)
示例#30
0
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)
示例#31
0
文件: views.py 项目: go4math/soup
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]))
示例#32
0
文件: routes.py 项目: olaborde/klik
def create_comments():
    companyName = request.form.get('companyName', "")
    user_id = request.form.get('user_id', "")
    feedback = request.form.get('feedback', "")
    companyName = request.form.get('companyName', "")
    rating = request.form.get('rating', "")
    newComment = Comment(feedback, companyName, rating, user_id)
    db.session.add(newComment)
    db.session.commit()
    return redirect("/")
示例#33
0
文件: views.py 项目: 0x4cc/MicroBlog
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)))
示例#34
0
    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)
示例#35
0
文件: views.py 项目: yuucu/burp_test
def add_comment():
  text = flask.request.form['text']
  if text == '':
    pass
  else:
    comment = Comment(
      text = text
    )
    db.session.add(comment)
    db.session.commit()
  return flask.redirect(url_for('index'))
示例#36
0
文件: views.py 项目: Lootgvfr/lotr
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))
示例#37
0
文件: views.py 项目: yotamoron/blog
def view(request, post_id):
        the_post = get_post_by_id(post_id)
        if not the_post:
                return message(request, "The post you asked for doesn't exist")
        if request.method == "POST":
                the_comment = Comment()
                the_comment.on_post_id = the_post.id
                the_comment.user_id = request.user.id
                form = CommentForm(request.POST, instance=the_comment)
                if form.is_valid():
                        form.save()
                        return HttpResponseRedirect(reverse('main.views.view',
                                args=(post_id,)))
        comments = Comment.objects.filter(on_post__id=the_post.id).order_by('posted_at')
        d = {'post':the_post, 'comments':comments}
        if request.user.is_authenticated():
                d['comment_form'] = CommentForm()
        the_post.views += 1
        the_post.save()
        return render_to_response(request, 'view.html', d,
                        context_instance=RequestContext(request))
示例#38
0
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)
示例#39
0
文件: comments.py 项目: swordwj/weigo
def delComment(postid, commid, host):
    if session.get('username') != host:
        return render_template('notlogin.html')

    else:
        # 删除comment
        sql_del = 'DELETE FROM comment WHERE comment_id = %s;'
        parm_del = (commid, )
        Comment().set_Comment(sql_del, parm_del)

        return redirect(
            url_for('comment', postid=postid, commid=commid, host=host))
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!")
示例#41
0
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)
示例#42
0
文件: views.py 项目: petrosdbz20/pp
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}))
示例#43
0
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))
示例#44
0
文件: comment.py 项目: alexdiao/3805
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
示例#45
0
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))
示例#46
0
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))
示例#47
0
文件: comment.py 项目: alexdiao/3805
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)