Exemplo n.º 1
0
def detail(request, pk):
    d = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post=d)
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CommentForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            comment = form.cleaned_data['comment']
            # print(comment,pk)
            #save comment in Comment model that is in data base
            c = Comment(post=d, comment=comment, user=request.user)
            c.save()
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            context = {'post': d, 'form': form, 'comments': comments}
            return render(request, 'detail.html', context)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CommentForm()
    context = {'post': d, 'form': form, 'comments': comments}
    return render(request, 'detail.html', context)
Exemplo n.º 2
0
def detail(request, pk):
    p = Post.objects.get(pk=pk)
    comments = Comment.objects.filter(post_id=pk)
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CommentForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            comment = form.cleaned_data['comment']
            c = Comment(post_id=pk, comment=comment, user=request.user)
            c.save()
            # redirect to a new URL:
            return HttpResponseRedirect(
                reverse('myapp:detail', kwargs={'pk': pk}))

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CommentForm()

    return render(request, 'detail.html', {
        'form': form,
        'p': p,
        'comments': comments
    })
Exemplo n.º 3
0
def add_comment(request):
    if request.method == 'POST':
        try:
            payload = json.loads(request.body)
            comment_id = uuid.uuid4().hex[:10]
            post_id = payload['post_id']
            body = payload['body']
            posted_by = payload['posted_by']
            parent_id = payload['parent_id']
            posted_date = int(time.time())

            post = get_object_or_404(Post, post_id=post_id)
            post.last_posted_by = posted_by
            post.last_posted_date = posted_date
            post.replies = F('replies') + 1
            post.save()

            comment = Comment(comment_id, post_id, body, posted_by,
                              posted_date, parent_id)
            comment.save()

            response = json.dumps([{
                'success': 'Comment added successfully!',
                'commentid': comment_id
            }])
        except:
            response = json.dumps([{'error': 'Comment  could not be added!'}])
        return HttpResponse(response, content_type='text/json')
    else:
        response = json.dumps([{'error': 'Comment could not be added!'}])
        return HttpResponse(response, status='404', content_type='text/json')
Exemplo n.º 4
0
def comment(request):
    errors = {}
    valid, data = validate_session(request)
    if not valid:
        return data
    if request.method == 'POST':
        try:
            body = json.loads(request.body)
            comment_id = 'c_' + str(uuid.uuid4())
            dweet_id = body['dweet_id']
            comment_data = body['comment']
            created_time = str(datetime.datetime.now())
            account_id = data
            comment = Comment(comment_id=comment_id,
                              dweet_id=dweet_id,
                              comment_data=comment_data,
                              created_time=created_time,
                              account_id=account_id)
            comment.save()
            return getResonse({"status": "success"}, 201)
        except KeyError as ke:
            print ke
            return getResonse({
                "status": "failed",
                "data_missing": ke.message
            }, 422)
        except Exception as e:
            print e
            return getResonse({"status": "failed"}, 500)
    else:
        return getResonse({"status": "failed"}, 405)
Exemplo n.º 5
0
def add_comment(index):
    content = request.form.get('comment_content')
    comment = Comment(content=content)
    comment.user_id = g.user.id
    comment.article_id = index
    # comment.reply_type = 1
    db.session.add(comment)
    db.session.commit()
    flash('Submit comments successfully.')
    return redirect(url_for('detail', index=index))
Exemplo n.º 6
0
def postComment(request):
    if request.method == 'POST':
        comments = request.POST.get("comment")
        user = request.user
        postSno = request.POST.get("postSno")
        post = Post.objects.get(sno=postSno)
        comments = Comment(comments=comments, user=user, post=post)
        comments.save()
        messages.success(request, "Your comment has been posted")

    return redirect(f"/blog/{post.slug}")
Exemplo n.º 7
0
def add_comment(request, id):
    token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
    payload = jwt_decode_handler(token)
    user_id = payload['user_id']
    try:
        user = User.objects.get(pk=user_id)
        post = Post.objects.get(pk=id)
        comment = Comment(user=user, post=post, text=request.data['text'])
        comment.save()
        return Response('Success', status=status.HTTP_201_CREATED)
    except Exception:
        return Response('Error', status.HTTP_401_UNAUTHORIZED)
Exemplo n.º 8
0
def reply(index,user_name):
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(content=form.content.data)
        comment.user_id = g.user.id
        comment.article_id = index  #
        # comment.reply_type = 2
        comment.to_user = user_name
        db.session.add(comment)
        db.session.commit()
        flash('Submit reply successfully.')
        return redirect(url_for('detail', index=index))
    return render_template('reply.html', title='Reply', form=form)
Exemplo n.º 9
0
def send_comment(post_id, comment_user, comment_text, comment_image):
    usr = User.objects.get(id=comment_user)
    ps = Post.objects.get(id=post_id)

    import uuid
    nameFile = str(uuid.uuid4())[:12]
    imgstr = re.search(r'base64,(.*)', comment_image).group(1)
    # path = default_storage.save('%s.png' % nameFile, ContentFile(imgstr))
    img_file = open("media/%s.png" % nameFile, 'wb')
    img_file.write(base64.b64decode(imgstr))
    img_file.close()

    post = Comment()
    post.comment_text = comment_text
    post.comment_image = nameFile
    post.post_id = ps
    post.comment_user = usr
    post.save()

    user_post = str(usr.username)

    r = redis.StrictRedis()

    if user_post:
        r.publish(
            "".join(['post_', post_id, '_comments']),
            json.dumps({
                "user_post": user_post,
                "title": comment_text,
            }))
Exemplo n.º 10
0
def comment_list(page):
    per_page_data = 10
    if page is None:
        page = 1
    next_page = page + 1
    pre_page = page - 1
    data = Comment.comment_query(id=None,
                                 per_page=page,
                                 page_count=per_page_data)  #每页100条数据
    if int(Comment.query.count() / per_page_data) == 0:
        last_page = int(Comment.query.count() / per_page_data)
    else:
        last_page = int(Comment.query.count() / per_page_data) + 1
    comment = []
    for v in data:
        comment.append({
            'id': v[0],
            'user_name': v[1],
            'movie_title': v[2],
            'content': v[3],
            'addtime': v[4],
            'face': v[5]
        })

    return render_template('admin/comment_list.html',
                           comment=comment,
                           last_page=last_page,
                           page=page,
                           next_page=next_page,
                           pre_page=pre_page)
Exemplo n.º 11
0
def comment(request):
    if request.method == 'POST':
        r_userid = request.META.get("HTTP_USERID")
        r_parentid = request.POST.get("parentId", '')
        r_content = request.POST.get("content", '')
        r_type = request.POST.get("type", 1)
        if len(r_content) == 0:
            return JsonResponse(common.build_result(CLIENT_ERROR, "内容为空"),
                                safe=False)
        q_blog = MicroBlog.objects.filter(blogId=r_parentid)
        if r_type == 1 and len(q_blog) == 0:
            return JsonResponse(common.build_result(CLIENT_ERROR, "博客不存在"),
                                safe=False)
        q_user = User.objects.filter(userId=r_userid)[0]
        Comment(authorId=r_userid,
                authorName=q_user.nickname,
                authorAvatar=q_user.avatar,
                parentId=r_parentid,
                content=r_content,
                type=r_type).save()
        q_blog[0].commentCount = q_blog[0].commentCount + 1
        q_blog[0].save()
        return JsonResponse(common.build_result(SUCCESS, "success"))
    return JsonResponse(common.build_result(CLIENT_ERROR, ERROR_REQ_METHOD),
                        safe=False)
Exemplo n.º 12
0
def comment(txt_id):
    txt = Article.query.get_or_404(txt_id)
    if request.method == 'POST':
        com_name = request.form['nick']
        com_txt = request.form['com_txt']
        if not com_name or not com_txt:
            flash('請輸入暱稱或內容...')
            return redirect(url_for('comment'))
        if len(com_txt) > 100:
            flash('內容請勿超過100個字元...')
            return redirect(url_for('comment'))
        nickname = Nickname.query.filter_by(name=com_name).first()
        if not nickname:
            flash('暱稱不存在...')
            return redirect(url_for('commit'))
        else:
            com_txt = Comment(com_txt=com_txt)
            nickname.n_comment.append(com_txt)
            txt.a_comment.append(com_txt)
            db.session.add(nickname)
            db.session.add(txt)
        db.session.commit()
        flash('回覆成功...')
        return redirect(url_for('comment', txt_id=txt_id))
    com_addtxt = txt.a_comment
    return render_template('comment.html',
                           com_txts=com_addtxt,
                           current_time=datetime.utcnow())
Exemplo n.º 13
0
def home(request, articleType,url='/'):
        request.session.set_expiry(0)
        username = request.session.get('username', False)
        print(username)
        if not username:
            pass#username = '******'
        if request.method == "POST":
            comment=Comment()
            comment.username=request.session.get('username', False)
            if url == '/':
                blog_list = BlogsPost.objects.filter(artcileType=articleType)
                thisBlog = BlogsPost.objects.get(title=blog_list[0].title)
                comment.title=thisBlog.title
                comment.time=datetime.datetime.now() 
            else:
                thisBlog = BlogsPost.objects.get(title=url)
                thisBlog.commentNum=thisBlog.commentNum+1;
                thisBlog.save();
                comment.title=thisBlog.title
                comment.time=datetime.datetime.now()
            comment.userimg='/static/img/jslogo.jpg'
            comment.body=request.POST.get('content',False)
            comment.save()
            if url=='/':
                comments=Comment.objects.filter(title=blog_list[0].title)
                return HttpResponseRedirect('/', {'posts': blog_list, 'post': blog_list[0], 'username': username,'comments':comments})
            else:
                blog_list = BlogsPost.objects.filter(artcileType=articleType)
                thisBlog = BlogsPost.objects.get(title=url)
                comments=Comment.objects.filter(title=thisBlog.title)
                return HttpResponseRedirect(url, {'post': thisBlog, 'posts': blog_list, 'username': username,'comments':comments})
        else:
            blog_list = BlogsPost.objects.filter(artcileType=articleType)
            for blog in blog_list:
                blog.url = "/article/" +blog.artcileType + '/'+blog.title
            if url == '/':
                comments=Comment.objects.filter(title=blog_list[0].title)
                #print(blog_list[0].body)
                return render_to_response('home.html', {'posts': blog_list, 'post': blog_list[0], 'username': username,'comments':comments})
            else:
                thisBlog = BlogsPost.objects.get(title=url)
                thisBlog.readNum =thisBlog.readNum+1
                thisBlog.save()
                comments=Comment.objects.filter(title=thisBlog.title)
                return render_to_response('home.html', {'post': thisBlog, 'posts': blog_list, 'username': username,'comments':comments})
Exemplo n.º 14
0
def main():
    from myapp.models import Subject
    from myapp.models import User
    from myapp.models import Comment
    i = 0
    all = []
    for line in f:
        i += 1
        data = ''
        try:
            data = json.loads(line)
        except:
            error.write(line + '\n')
            line = line.replace('\\', '\\\\').replace('\r', ' ').replace('\n', ' ').replace('\t', ' ')
            data = json.loads(line)
            error.write('----' + line + '\n')
            error.flush()
        user_name = data['user_name']
        sid = data['sid']
        user = ''
        subject = ''
        try:
            user = User.objects.get(user_name=user_name)
            subject = Subject.objects.get(id=sid)
        except:
            error.write('not exists ------ ' + line + '\n')
            error.flush()
            continue
        key = user_name + '|' + str(sid)
        if key in duplicate:
            error.write('duplicate ------' + line + '\n')
            error.flush()
            continue
        else:
            duplicate[key] = 1
        time = data['time']
        time = time.split(' ')[0].split('-')
        dt2 = datetime.datetime(int(time[0]), int(time[1]), int(time[2]))
        timeid = (dt2 - dt1).days
        timeid = (timeid + 6) / 7 * 7
        all.append(Comment(
            user=user,
            subject=subject,
            star=data['star'],
            time=data['time'],
            timeid=timeid,
            content=data['comment']
        ))
        if i % 20000 == 0:
            print i
            Comment.objects.bulk_create(all)
            all = []

    Comment.objects.bulk_create(all)
    f.close()
    error.close()
Exemplo n.º 15
0
def index(request):
  form = CommentForm()
  if request.method == "POST" and form.validate(request.form):
    form.save()
    return redirect(url_for('myapp/index'))
  query = Comment.all().order('-created')
  comments = query.fetch(ITEMS_PER_PAGE)
  return render_to_response('myapp/index.html',
                            {'form': form.as_widget(),
                             'comments': comments})
Exemplo n.º 16
0
def main_page(request, country_code="global"):

    file = open('spotify_countries.json')
    countries = json.load(file)
    comments = Comment.objects.all().order_by("date")

    if country_code == None:
        country_code = "global"

    top_ten = get_top_ten(country_code)

    login_form = AuthenticationForm(request.POST)

    if request.method == 'GET' and request.is_ajax():

        data = dict(request.GET)
        first = next(iter(data.keys()))
        print(first)

        if first == 'Song':
            song = data['Song'][0]
            artist = data['Artist'][0]
            #call get_lyrics scraper
            lyrics = get_lyrics(song, artist)
            return HttpResponse(lyrics, content_type="text")

    if request.method == 'POST' and request.is_ajax():
        json_response = json.loads(request.body)
        if json_response["messageType"] == "comment":
            comment = json_response["comment"]
            user = json_response["user"]
            new_comment = Comment(user=user, comment=comment)
            new_comment.save()
            response = "< " + user + " >: " + comment
            return HttpResponse(response)

    return render(
        request, 'base.html', {
            'login_form': login_form,
            'top_tracks': top_ten,
            'countries': countries,
            'comments': comments
        })
Exemplo n.º 17
0
def comment_edit(request, song_id, comment_id=None):
    """コメントの編集"""
    song = get_object_or_404(Song, pk=song_id)  # 親の曲を読む
    # comment_idが指定されている(修正時)
    if comment_id:
        comment = get_object_or_404(Comment, pk=comment_id)
    # comment_idが指定されていない(追加時)
    else:
        comment = Comment()

    if request.method == 'POST':
        # POSTされたrequestデータからフォームを作成
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.song = song
            comment.save()
            return redirect('myapp:comment_list', song_id=song_id)
    else:  # GETの時
        form = CommentForm(instance=comment)

    return render(request, 'myapp/comment_edit.html',
                  dict(form=form, song_id=song_id, comment_id=comment_id))
Exemplo n.º 18
0
def commenter(content, post_id):
    post = Post.query.get_or_404(post_id)
    author = post.author
    comment = Comment(content=content, author=current_user, post_id=post_id)
    db.session.add(comment)
    db.session.commit()
    post.nbrcomments += 1
    if not current_user == author:
        #notif=Notif.query.filter_by(title='PostCommented').first()
        #author.notifs.append(notif)
        # author.getnot+=1
        db.session.commit()
    flash('Your comment has been added', 'success')
    return redirect(url_for('posts.post', post_id=post.id))
Exemplo n.º 19
0
def play(id,page):
    movie=Movie.query.filter_by(id=id).first()
    if movie:
        movie.playnum=int(movie.playnum)+1
        Movie.add_comment_or_play(movie)
        form=AddComment()
        if form.validate_on_submit():
            if not session['user_id']:
                return redirect(url_for('home.login'))
            data=form.data
            if data['content']:
                comment=Comment(
                    user_id=session['user_id'],
                    movie_id=id,
                    addtime=datetime.datetime.now(),
                    content=data['content']
                )
                if Comment.addcomment(comment):
                    flash("添加评论成功!",'ok')
                    movie.commentnum=int(movie.commentnum)+1
                    Movie.add_comment_or_play(movie)
                    return redirect(url_for('home.play',id=id,page=page))
        shoucang=AddMoviecol()
        if shoucang.validate_on_submit():
            if not Moviecol.query.filter_by(user_id=session['user_id'],movie_id=id).count():
                if Moviecol.moviecol_add(session['user_id'],id):
                    flash("收藏成功!",'ok')
                    return redirect(url_for('home.play',id=id,page=page))
            else:
                if Moviecol.moviecol_del_by_user(session['user_id'],id):
                    flash("取消收藏!",'err')
                    return redirect(url_for('home.play',id=id,page=page))
        pre_page_date=20     #每页20条数据
        comment_count=Comment.query.filter_by(movie_id=id).count() #评论总数
        page_data=Movie.query.filter_by(id=id).first_or_404()
        tag=Tag.query.filter_by(id=page_data.tag_id).first_or_404()
        tag_name=tag.name
        if page is None:
            page=1
        next_page=page+1
        pre_page=page-1
        data=Comment.comment_query(id=id,per_page=page,page_count=pre_page_date)
        if int(comment_count/pre_page_date)==0:
            last_page=int(comment_count/pre_page_date)
        else:
            last_page=int(comment_count/pre_page_date)+1
        comment=[]
        for v in data:
            comment.append({
                'id':v[0],
                'user_name':v[1],
                'movie_title':v[2],
                'content':v[3],
                'addtime':v[4],
                'face':v[5]
            })
    return render_template('home/play.html',shoucang=shoucang,id=id,form=form,page_data=page_data,tag_name=tag_name,comment=comment,last_page=last_page,page=page,next_page=next_page,pre_page=pre_page,comment_count=comment_count)
Exemplo n.º 20
0
def comment_del(id):  #删除评论
    comment = Comment.query.filter_by(id=id).first()
    user_name = User.query.filter_by(id=comment.user_id).first()
    movie_name = Movie.query.filter_by(id=comment.movie_id).first()
    if Comment.comment_del(id):
        op_log_list = Oplog(
            admin_id=int(session['admin_id']),
            addtime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            ip=request.remote_addr,
            reason="删除 %s 对电影 %s 的评论:%s 成功" %
            (user_name, movie_name, comment.content))
        Oplog.add_log(op_log_list)  #加入日志
        flash('评论删除成功!', 'ok')
        return redirect(url_for('admin.comment_list', page=1))
    return redirect(url_for('admin.comment_list', page=1))
Exemplo n.º 21
0
def add_comment_reply(userid):
    course_id = request.get_json()['course_id']
    content = request.get_json()['content']
    to_user_id = request.get_json()['to']

    comment_new = Comment(course_id=course_id,
                          content=content,
                          from_user_id=userid,
                          from_user_type=2,
                          to_user_id=to_user_id,
                          to_user_type=1)

    db.session.add(comment_new)
    db.session.commit()

    return Resp.success()
Exemplo n.º 22
0
    def post(self):
        """ Actions to post, edit, and update comments on the post. """

        user_name = self.user.name
        # Post a comment
        if self.request.get('comment'):
            comment = self.request.get('comment')  # comment content
            author = user_name
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment = Comment(author=author, comment=comment, parent=post.key)
            comment.put()
            self.redirect('/post?post_id=' + post_id)
        # Delete an existing comment
        elif self.request.get('delete'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('delete'))
            comment_to_delete = Comment.get_by_id(comment_id, parent=post.key)
            comment_to_delete.key.delete()
            self.redirect('/post?post_id=' + post_id)
        # Edit an existing comment
        elif self.request.get('edit'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('edit'))
            comment_to_edit = Comment.get_by_id(comment_id, parent=post.key)
            if self.user.name == comment_to_edit.author:  # Verify user is author
                self.render('editcomment.html',
                            comment=comment_to_edit,
                            user_name=user_name,
                            comment_id=comment_id,
                            post_id=post_id)
                return
            else:
                self.redirect('/post?post_id=' +
                              post_id)  # Wish I could flash error msg

        elif self.request.get('update'):
            post_id = self.request.get('post_id')
            post = Post.by_id(int(post_id))
            comment_id = int(self.request.get('update'))
            comment_to_update = Comment.get_by_id(comment_id, parent=post.key)
            updated_comment_contents = self.request.get('updated-comment')
            updated_comment_contents = cgi.escape(updated_comment_contents)
            comment_to_update.comment = updated_comment_contents
            comment_to_update.put()
            self.redirect('/post?post_id=' + post_id)
        else:
            self.redirect('/')
Exemplo n.º 23
0
def post_comment(post_id):
    """
    本文表示、個別ページ post_idから対応するPOSTのデータをDBからとって表示
    本文したにコメント表示
    """
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(author=current_user,
                          post_on=datetime.now(),
                          body=form.body.data,
                          post_id=post_id)
        db.session.add(comment)
        db.session.commit()
        print("comment post success")
        return redirect('/{:d}'.format(post_id))
    return render_template('editor.html', form=form)
Exemplo n.º 24
0
def make_comment(current_user):
    if current_user is not None:
        if request.method == 'POST':
            parsejson = request.get_json()
            commentlist = {}
            newcomment = {"comment_body": parsejson['body']}
            postid = request.args['id']
            userid = current_user.id
            user = User.query.get(userid)
            username = user.username
            post = Post.query.filter_by(id=postid)
            comment = Comment(comment_body=newcomment['comment_body'],
                              usercomment=user,
                              postcomments=post)
            db.session.add(comment)
            db.session.commit()
    return jsonify(commentlist)
Exemplo n.º 25
0
def add_comment(userid):
    course_id = request.get_json()['course_id']
    content = request.get_json()['content']
    course = Course.query.get(course_id)

    comment_new = Comment(
        course_id=course_id,
        content=content,
        from_user_id=userid,
        from_user_type=1,
        to_user_id=course.admin_id,
        to_user_type=2
    )

    db.session.add(comment_new)
    db.session.commit()

    return Resp.success()
Exemplo n.º 26
0
 def get(self, **kw):
     post_id = self.request.get('post_id')
     post = Post.by_id(int(post_id))
     comments = Comment.query(ancestor=post.key)
     comments = comments.order(-Comment.created)
     comments = comments.fetch(5)
     user_name = ""
     user_is_author = False
     if self.user:
         user_name = self.user.name
         if post.author and user_name == post.author:
             user_is_author = True
     self.render('viewpost.html',
                 post=post,
                 user_name=user_name,
                 user_is_author=user_is_author,
                 comments=comments,
                 **kw)
Exemplo n.º 27
0
def add_stock_comment(request):
    """This function adds comments to Comments table for a specific stock .

	**Template:**

	:template:'myapp/templates/signle_stock.html'
	"""
    if request.method == 'POST':

        if request.POST.get('name') and request.POST.get('content'):
            comment = Comment()
            comment.author = request.POST.get('name')
            comment.text = request.POST.get('content')
            comment.stock_id = request.POST.get('stock_symbol')
            symbol = request.POST.get('stock_symbol')
            comment.save()

            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Exemplo n.º 28
0
def play(id,page=None):
    movie = Movie.query.get(id)
    if page ==  None:
        page = 1
    comments = Comment.query.filter(and_(Comment.movie_id==movie.id,Comment.user_id==User.id)).order_by(Comment.addtime.desc()).paginate(page,limits)
    form = CommentForm()
    if form.validate_on_submit():
        data = form.data
        comment = Comment(
            content= data['content'],
            movie_id = movie.id,
            user_id = session['user_id']
        )
        movie.commentnum += 1                       # 评论数量 + 1
        db.session.add(movie)
        db.session.add(comment)
        db.session.commit()
        flash('提交评论成功!','ok')
        return redirect(url_for('project.play',id=movie.id,page=1))
    movie.playnum += 1                              # 播放数量 + 1
    db.session.add(movie)
    db.session.commit()
    moviecol = Moviecol.query.filter(Moviecol.user_id==session['user_id'],Moviecol.movie_id==id).first()
    return render_template('home/play.html',movie=movie,form=form,comments=comments,moviecol=moviecol)
Exemplo n.º 29
0
def index(request):
    if request.method == "GET":
        vCourse_id = request.GET["course_id"]
        author_id = request.GET["user_id"]
        author = User.objects.get(id=author_id)
        cl = Curriculumn.objects(id=vCourse_id)
        has_curriculum = False
        try:
            is_mentor = request.session["is_mentor"]
        except Exception as e:
            is_mentor = False
        user = User.objects.get(username=str(request.user))
        student = Student.objects(user=user.id)
        status = "1"

        if len(cl):
            has_curriculum = True

        clTaken = 0
        clLike = 0
        mtTaken = 0
        mtLike = 0
        actTaken = 0
        actLike = 0
        mtTotal = 0
        actTotal = 0

        is_joined = False
        if len(student):
            progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student[0].id)
            if len(progress) > 0:
                is_joined = True
        lscl = []
        lscl = cl[0]

        for i in lscl.__getattribute__("material"):
            i.note = "0"
            try:
                is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id)
                if len(is_like):
                    i.note = "1"
                    i.__getattribute__("statistic").currentLikeNumber -= 1
            except Exception as e:
                print(e)
        avatar = ""
        try:
            avatar = request.session["avatar"]
        except Exception as e:
            request.session["avatar"] = ""
            print(e)

        context = {
            "cl": lscl,
            "is_joined": is_joined,
            "user_id": request.user,
            "course_id": vCourse_id,
            "author_id": author_id,
            "author": author.username,
            "is_mentor": is_mentor,
            "clTaken": clTaken,
            "clLike": clLike,
            "mtTaken": mtTaken,
            "mtLike": mtLike,
            "actTaken": actTaken,
            "actLike": actLike,
            "mtTotal": mtTotal,
            "actTotal": actTotal,
            "has_curriculum": has_curriculum,
            "avatar": avatar,
        }
        return render(request, "myapp/course-detail.html", context)
    elif request.method == "POST":
        if request.POST["posttype"] == "likeMaterial":
            user = User.objects.get(username=str(request.user))
            print(request.POST["posttype"])
            materialId = request.POST["materialId"]
            status = request.POST["status"]  # like or dislike

            # update status=0 for recors last with status=1,user_id,material
            sdLast = StatisticDetail.objects(user=user.id, object_id=str(materialId), status="1").order_by(
                "published_date"
            )[:10]
            if len(sdLast):
                for sdUpdate in sdLast:
                    sdUpdate.status = "0"
                    sdUpdate.save()
            else:
                print("no update ")
            sdNew = StatisticDetail()
            sdNew.user = user
            sdNew.object_id = str(materialId)
            if status == "0":
                sdNew.status = "1"
            else:
                sdNew.status = "0"
            sdNew.save()
            # update or insert statistic
            stCurent = Statistic.objects(object_id=str(materialId)).order_by("create_date")[:1]
            stNew = Statistic()
            if len(stCurent) > 0:
                stNew = stCurent[0]
                if status == "1":
                    stNew.currentLikeNumber -= 1
                else:
                    stNew.currentLikeNumber += 1
                stNew.type = "1"
                stNew.save()
            else:
                if status == "0":
                    stNew.currentLikeNumber = 1
                else:
                    stNew.currentLikeNumber = 0
                stNew.object_id = str(materialId)
                stNew.type = "1"
                stNew.save()
                # update material
            mtCurrent = Material.objects.get(id=materialId)
            mtCurrent.statistic = stNew
            mtCurrent.note = "0"
            mtCurrent.save()

            return HttpResponse(json.dumps({"formdata": materialId}), content_type="application/json")
        elif request.POST["posttype"] == "frmJoincourse":
            curriculum_id = request.POST["curriculum_id"]
            user_id = request.POST["user_id"]
            print(curriculum_id)
            curriculum = Curriculumn.objects.get(id=curriculum_id)

            user = User.objects.get(username=str(request.user))
            student = Student.objects(user=user.id)

            planstart = request.POST["planstart"]
            planend = request.POST["planend"]
            impression = request.POST["impression"]
            description = request.POST["description"]
            # Save CurriculumnStudyProgress
            csp = CurriculumnStudyProgress()
            if len(student):
                st = student[0]
                csp.student = st
            csp.curriculumn = curriculum
            csp.PlanStartDate = datetime.strptime(planstart, "%m/%d/%Y")
            csp.PlanEndDate = datetime.strptime(planend, "%m/%d/%Y")
            csp.impression = Impression.objects.get(showpiority=impression)
            csp.description = description
            csp.save()

            # UPDATE Curriculumn
            print(user.id)
            curri = Curriculumn()

            curri = Curriculumn.objects.get(id=curriculum_id)
            curri.joined_user.append(user)

            curri.save()
            # Save CurriculumnLog
            lisProgressType = ProgressType.objects().order_by("rate")
            progressType = lisProgressType[0]

            curriLog = CurriculumnLog()

            curriLog.curriculumn = curri
            curriLog.process = progressType
            curriLog.data = "[]"
            curriLog.user_id = user

            curriLog.save()
            # SHOW Record
            cl = Curriculumn.objects(id=curriculum_id)
            has_curriculum = False
            is_mentor = False
            mentor = Mentor.objects(user=user.id)
            if len(mentor):
                is_mentor = True
            if len(cl):
                has_curriculum = True
            print(has_curriculum)
            clTaken = 0
            clLike = 0
            mtTaken = 0
            mtLike = 0
            actTaken = 0
            actLike = 0
            mtTotal = 0
            actTotal = 0
            try:
                for c in cl:
                    if c.statistic.currentTakenNumber:
                        clTaken += c.statistic.currentTakenNumber
                    if c.statistic.currentLikeNumber:
                        clLike += c.statistic.currentLikeNumber
                    for mt in c.material:
                        if mt.statistic.currentTakenNumber:
                            mtTaken += mt.statistic.currentTakenNumber
                        if mt.statistic.currentLikeNumber:
                            mtLike += mt.statistic.currentLikeNumber
                            mtTotal += 1
                    for act in c.action:
                        if act.statistic.currentTakenNumber:
                            actTaken += act.statistic.currentTakenNumber
                        if act.statistic.currentLikeNumber:
                            actLike += act.statistic.currentLikeNumber
                            actTotal += 1
            except Exception as e:
                print(e)
            is_joined = False
            if len(student):
                progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student[0].id)
                if len(progress) > 0:
                    is_joined = True
            context = {
                "cl": cl[0],
                "is_joined": is_joined,
                "user_id": request.user,
                "course_id": curriculum_id,
                "author": user.username,
                "is_mentor": is_mentor,
                "clTaken": clTaken,
                "clLike": clLike,
                "mtTaken": mtTaken,
                "mtLike": mtLike,
                "actTaken": actTaken,
                "actLike": actLike,
                "mtTotal": mtTotal,
                "actTotal": actTotal,
                "has_curriculum": has_curriculum,
            }
            return HttpResponseRedirect("course-detail?course_id=" + curriculum_id + "&user_id=" + user_id)
        elif request.POST["posttype"] == "deleteComment":
            try:
                comment_status = "0"
                comment_id = request.POST["hd_comment_id"]
                course_id = request.POST["hd_course_id"]
                author_id = request.POST["hd_author_course_id"]
                user_id = request.session["_auth_user_id"]

                cmt = Comment.objects.get(id=comment_id)
                cmt.status = comment_status
                cmt.save()
                status = "1"
                author = User.objects.get(id=author_id)
                cl = Curriculumn.objects(id=course_id)
                has_curriculum = False
                is_mentor = request.session["is_mentor"]
                user = User.objects.get(username=str(request.user))
                student = Student.objects.get(user=user.id)

                clTaken = 0
                clLike = 0
                mtTaken = 0
                mtLike = 0
                actTaken = 0
                actLike = 0
                mtTotal = 0
                actTotal = 0
                try:
                    for c in cl:
                        if c.statistic.currentTakenNumber:
                            c.statistic.currentTakenNumber = 10
                            clTaken += c.statistic.currentTakenNumber
                        if c.statistic.currentLikeNumber:
                            clLike += c.statistic.currentLikeNumber

                        for mt in c.material:
                            if mt.statistic.currentTakenNumber:
                                mtTaken += mt.statistic.currentTakenNumber
                            if mt.statistic.currentLikeNumber:
                                mtLike += mt.statistic.currentLikeNumber
                                mtTotal += 1
                            print(mt.name)
                        for act in c.action:
                            if act.statistic.currentTakenNumber:
                                actTaken += act.statistic.currentTakenNumber
                            if act.statistic.currentLikeNumber:
                                actLike += act.statistic.currentLikeNumber
                                actTotal += 1
                except Exception as e:
                    print(e)

                progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student.id)
                is_joined = False
                if len(progress) > 0:
                    is_joined = True

                lscl = []
                lscl = cl[0]
                for i in lscl.__getattribute__("material"):
                    i.note = "0"
                    try:
                        is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id)
                        if len(is_like):
                            i.note = "1"
                            i.__getattribute__("statistic").currentLikeNumber -= 1
                    except Exception as e:
                        print(e)

                context = {
                    "cl": lscl,
                    "is_joined": is_joined,
                    "user_id": request.user,
                    "course_id": course_id,
                    "author_id": author_id,
                    "author": author.username,
                    "is_mentor": is_mentor,
                    "clTaken": clTaken,
                    "clLike": clLike,
                    "mtTaken": mtTaken,
                    "mtLike": mtLike,
                    "actTaken": actTaken,
                    "actLike": actLike,
                    "mtTotal": mtTotal,
                    "actTotal": actTotal,
                    "has_curriculum": has_curriculum,
                }
            except Exception as e:
                print(e)
            finally:
                return render(request, "myapp/course-detail.html", context)
        elif request.POST["posttype"] == "editComment":
            try:
                comment = request.POST["txtcommentName"]
                comment_id = request.POST["hd_comment_id"]
                course_id = request.POST["hd_course_id"]
                author_id = request.POST["hd_author_course_id"]
                user_id = request.session["_auth_user_id"]

                cmt = Comment.objects.get(id=comment_id)
                cmt.content = comment
                cmt.save()
                status = "1"
                author = User.objects.get(id=author_id)
                cl = Curriculumn.objects(id=course_id)
                has_curriculum = False
                is_mentor = request.session["is_mentor"]
                user = User.objects.get(username=str(request.user))
                student = Student.objects.get(user=user.id)

                clTaken = 0
                clLike = 0
                mtTaken = 0
                mtLike = 0
                actTaken = 0
                actLike = 0
                mtTotal = 0
                actTotal = 0
                try:
                    for c in cl:
                        if c.statistic.currentTakenNumber:
                            c.statistic.currentTakenNumber = 10
                            clTaken += c.statistic.currentTakenNumber
                        if c.statistic.currentLikeNumber:
                            clLike += c.statistic.currentLikeNumber

                        for mt in c.material:
                            if mt.statistic.currentTakenNumber:
                                mtTaken += mt.statistic.currentTakenNumber
                            if mt.statistic.currentLikeNumber:
                                mtLike += mt.statistic.currentLikeNumber
                                mtTotal += 1
                            print(mt.name)
                        for act in c.action:
                            if act.statistic.currentTakenNumber:
                                actTaken += act.statistic.currentTakenNumber
                            if act.statistic.currentLikeNumber:
                                actLike += act.statistic.currentLikeNumber
                                actTotal += 1
                except Exception as e:
                    print(e)

                progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student.id)
                is_joined = False
                if len(progress) > 0:
                    is_joined = True

                lscl = []
                lscl = cl[0]
                for i in lscl.__getattribute__("material"):
                    i.note = "0"
                    try:
                        is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id)
                        if len(is_like):
                            i.note = "1"
                            i.__getattribute__("statistic").currentLikeNumber -= 1
                    except Exception as e:
                        print(e)

                context = {
                    "cl": lscl,
                    "is_joined": is_joined,
                    "user_id": request.user,
                    "course_id": course_id,
                    "author_id": author_id,
                    "author": author.username,
                    "is_mentor": is_mentor,
                    "clTaken": clTaken,
                    "clLike": clLike,
                    "mtTaken": mtTaken,
                    "mtLike": mtLike,
                    "actTaken": actTaken,
                    "actLike": actLike,
                    "mtTotal": mtTotal,
                    "actTotal": actTotal,
                    "has_curriculum": has_curriculum,
                }
            except Exception as e:
                print(e)
            finally:
                return render(request, "myapp/course-detail.html", context)
        else:
            comment = request.POST["txtComment"]
            course_id = request.POST["hd_course_id"]
            material_id = request.POST["hd_material_id"]
            user_id = request.session["_auth_user_id"]
            author_id = request.POST["hd_author_course_id"]
            ur = request.user
            cmt = Comment()
            cmt.user = request.user
            cmt.content = comment
            cmt.save()
            cl = Curriculumn.objects.get(id=course_id)
            mt = Material.objects.get(id=material_id)
            mt.comment.append(cmt)
            mt.save()
            cl.save()
            status = "1"
            print(author_id)
            author = User.objects.get(id=author_id)
            cl = Curriculumn.objects(id=course_id)
            has_curriculum = False
            is_mentor = request.session["is_mentor"]
            user = User.objects.get(username=str(request.user))
            student = Student.objects.get(user=user.id)

            clTaken = 0
            clLike = 0
            mtTaken = 0
            mtLike = 0
            actTaken = 0
            actLike = 0
            mtTotal = 0
            actTotal = 0
            try:
                for c in cl:
                    if c.statistic.currentTakenNumber:
                        c.statistic.currentTakenNumber = 10
                        clTaken += c.statistic.currentTakenNumber
                    if c.statistic.currentLikeNumber:
                        clLike += c.statistic.currentLikeNumber

                    for mt in c.material:
                        if mt.statistic.currentTakenNumber:
                            mtTaken += mt.statistic.currentTakenNumber
                        if mt.statistic.currentLikeNumber:
                            mtLike += mt.statistic.currentLikeNumber
                            mtTotal += 1
                        print(mt.name)
                    for act in c.action:
                        if act.statistic.currentTakenNumber:
                            actTaken += act.statistic.currentTakenNumber
                        if act.statistic.currentLikeNumber:
                            actLike += act.statistic.currentLikeNumber
                            actTotal += 1
            except Exception as e:
                print(e)

            progress = CurriculumnStudyProgress.objects(curriculumn=cl[0].id, student=student.id)
            is_joined = False
            if len(progress) > 0:
                is_joined = True

            lscl = []
            lscl = cl[0]
            for i in lscl.__getattribute__("material"):
                i.note = "0"
                try:
                    is_like = StatisticDetail.objects(object_id=str(i.id), status=status, user=user.id)
                    if len(is_like):
                        i.note = "1"
                        i.__getattribute__("statistic").currentLikeNumber -= 1
                except Exception as e:
                    print(e)

            context = {
                "cl": lscl,
                "is_joined": is_joined,
                "user_id": request.user,
                "course_id": course_id,
                "author_id": author_id,
                "author": author.username,
                "is_mentor": is_mentor,
                "clTaken": clTaken,
                "clLike": clLike,
                "mtTaken": mtTaken,
                "mtLike": mtLike,
                "actTaken": actTaken,
                "actLike": actLike,
                "mtTotal": mtTotal,
                "actTotal": actTotal,
                "has_curriculum": has_curriculum,
            }
            return render(request, "myapp/course-detail.html", context)
Exemplo n.º 30
0
    def handle(self, *args, **options):
        # now do the things that you want with your models here
        password = "******"
        exp_posts = 50
        exp_users = 20
        avg_votes_per_post = 5
        avg_comments_per_post = 3

        # Post.objects.all().delete()

        rootExists = User.objects.filter(username="******").count()
        if (rootExists < 1):
            self.stdout.write("Creating root user")
            User.objects.create_superuser("root", "*****@*****.**", password)

        num_posts = Post.objects.all().count()
        num_users = User.objects.all().count()
        num_votes = Vote.objects.all().count()
        num_comments = Comment.objects.all().count()

        faker = Faker()

        self.stdout.write("Default password: "******"Number of posts: " + str(num_posts))
        self.stdout.write("Number of votes: " + str(num_votes))
        self.stdout.write("Number of comments: " + str(num_comments))
        self.stdout.write("Number of users: " + str(num_users))

        if (num_users < exp_users):
            self.stdout.write("Creating " + str(exp_users - num_users) +
                              " Users")
            for x in range(num_users + 1, exp_users + 1):
                username = faker.name().replace(" ", ".")
                email = username + "@test.com"
                User.objects.create_superuser(username, email, password)
                self.stdout.write("   " + username)
            num_users = User.objects.all().count()

        if (num_posts < exp_posts):
            self.stdout.write("Creating " + str(exp_posts - num_posts) +
                              " Posts")
            for x in range(num_posts + 1, exp_posts + 1):
                day_offset = randint(1, 364)
                pub_date = timezone.now() - datetime.timedelta(days=day_offset)
                u = self.randomUser()
                title = faker.text()
                self.stdout.write("   [" + u.username + "] " + title)
                rec = Post()
                rec.author = u
                rec.title = title
                rec.text = faker.text()
                rec.created_date = pub_date
                rec.published_date = pub_date
                rec.save()
            num_posts = Post.objects.all().count()

        self.stdout.write("Voting...")
        while (num_votes < avg_votes_per_post * num_posts):
            user = self.randomUser()
            post = self.randomPost()
            voted = Vote.objects.all().filter(post=post, author=user).count()
            if (post.author != user and voted == 0):
                rec = Vote()
                rec.author = user
                rec.post = post
                rec.created_date = self.randomDate(post.created_date,
                                                   timezone.now())
                rec.save()
                num_votes = Vote.objects.all().count()
                self.stdout.write(
                    str(num_votes) + ": " + user.username + " voted for [" +
                    post.title + "]")

        self.stdout.write("Commenting...")
        while (num_comments < avg_comments_per_post * num_posts):
            user = self.randomUser()
            post = self.randomPost()
            rec = Comment()
            rec.author = user
            rec.post = post
            rec.contents = faker.text()
            rec.created_date = self.randomDate(post.created_date,
                                               timezone.now())
            rec.save()
            num_comments = Comment.objects.all().count()
            self.stdout.write(
                str(num_comments) + ": " + user.username + " commented on [" +
                post.title + "]")
Exemplo n.º 31
0
def commentview(request,id):
    x=request.POST['comment']
    s=Comment(message=x,MessageId_id=id)
    s.save()
    return HttpResponseRedirect('/myapp/article/%s'% id)
Exemplo n.º 32
0
def add_comment(request):
    post_id = request.POST['post']
    post = Post.objects.get(id = post_id)
    c = Comment(text = request.POST['text'])
    post.comment_set.add(c)
    return redirect('post', post_id)