Esempio n. 1
0
    def put(self, request, id, format=None):
        if id.startswith('commentID='):
            id = id[10:]
        else:
            return Response(
                {'Invalid id of comment.'},
                status=status.HTTP_404_NOT_FOUND)

        serializer = CommentSerializer(data=request.data)
        if serializer.is_valid() is False:
            return Response({
                'message': 'Cannnot update comment with provided information.'
            }, status=status.HTTP_400_BAD_REQUEST)

        comment = Comment.objects.filter(id=id).first()
        if comment is None:
            return Response(
                {'No comment has that id.'},
                status=status.HTTP_404_NOT_FOUND)

        self.check_object_permissions(request, comment)

        data = serializer.validated_data
        comment.content = data.get('content')
        comment.save()

        return Response(data, status=status.HTTP_200_OK)
def index(request):

	content = {
		'user': unicode(request.user),
		'auth': unicode(request.auth),
	}

	print 'User: '******'user']
	print 'Auth: ', content['auth']

	#node = Node.objects.get(node_user = content['user'])
	#print 'Node: ', node

	''' List all comments '''
	''' TODO: Why is this returning comments? '''



	if request.method == 'GET':
		comments = Comment.objects.all()
		serializer = CommentSerializer(comments, many=True)
		return Response({"comments": serializer.data})
	elif request.method == 'POST':
		serializer = PostSerializer(data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data, status=status.HTTP_201_CREATED)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 3
0
	def comments(self,request,pk):
		if request.method == 'GET':
			comments = self.get_object().comments
			serializer = CommentSerializer(comments, context={'request': request}, many=True)
			return Response(serializer.data)
		
		else:
			serializer = CommentSerializer(data=request.data)
			if serializer.is_valid():				
				serializer.save(owner=self.request.user, target=Catch.objects.get(id=pk))
				return Response(status=status.HTTP_204_NO_CONTENT)				
Esempio n. 4
0
 def post(self, request, format=None):
     '''
     Multiple comment sentiment classification:
     JSON_FORMAT:
     See JSON_FORMAT_for_REST_Service.txt for details on input/output json format
     '''
     serializer = CommentSerializer()
     print type(request.DATA)
     json_response = JSONClassificationResponse() 
     deserialized = serializer.deserialize(request.DATA)
     if deserialized:            
         return Response(json_response.classification_response(request.DATA), status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 5
0
 def get(self, request, format=None):
     '''
     Single comment sentiment classification:
     QUERY_PARAMS:
     comment: string comment
     classifier_type: 'SVM' or 'MNB'   
     classes: 2 or 5
     '''
     comment = request.QUERY_PARAMS.get('comment', 'comentario no encontrado :(')
     classifier_type = request.QUERY_PARAMS.get('classifier_type','SVM')
     no_classes = int(request.QUERY_PARAMS.get('no_classes', 5))
     classify = Classification()
     sentiment = classify.classify_comment(comment, classifier_type=classifier_type, no_classes=no_classes)
 	serializer = CommentSerializer()
 	serialized = serializer.serialize({comment:sentiment})
     return Response(serialized)
Esempio n. 6
0
    def post(self, request, id, format=None):
        if id.startswith('id='):
            id = id[3:]
        else:
            return Response(
                {'Invalid id of post.'},
                status=status.HTTP_404_NOT_FOUND)

        post = Post.objects.filter(id=id).first()
        # post = Post.objects.get(id=id)

        if post is None:
            return Response(
                {'No post with that id exists.'},
                status=status.HTTP_404_NOT_FOUND)

        serializer = CommentSerializer(data=request.data)

        if serializer.is_valid():
            data = serializer.validated_data

            author = A2AUser.objects.get(user__username=request.user.username)

            comment = Comment(parent=post, content=data.get('content'),
                              created_by=author)
            comment.save()

            # post.num_comments += 1
            # post.save()

            return Response(ExtraCommentSerializer(comment).data,
                            status=status.HTTP_201_CREATED)

        return Response({
            'status': 'Bad request',
            'message': 'Comment could not be created with received data.'
        }, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 7
0
class MovieSerializer(serializers.ModelSerializer):
    genres = GenreSerializer(many=True, read_only=True)
    actors = ActorSerializer(many=True, read_only=True)
    comments = CommentSerializer(many=True, read_only=True)

    class Meta:
        model = Movie
        fields = (
            'm_id',
            'adult',
            'poster_path',
            'title',
            'overview',
            'nation',
            'vote_average',
            'comment_score_sum',
            'comment_score_average',
            'release_date',
            'video_path',
            'genres',
            'actors',
            'comments',
            'like_users',
        )
class PostSerializer(serializers.ModelSerializer):
    """Detail serializer for the Post model"""
    category = CategoryIdSerializer(read_only=True)
    author = AuthorSerializer(read_only=True)
    comments = CommentSerializer(many=True)
    liked_readers = serializers.SerializerMethodField('get_liked_readers')
    tags = serializers.SerializerMethodField('get_tags')
    url = serializers.HyperlinkedIdentityField(view_name='post-detail')

    class Meta:
        model = Post
        fields = '__all__'

    def get_liked_readers(self, post_obj):
        """Get all readers' id who liked current post"""
        readers = [reader.id for reader in post_obj.liked_posts.all()]

        return readers

    def get_tags(self, post_obj):

        tags = [tag.name for tag in post_obj.tags.all()]

        return tags
Esempio n. 9
0
def comment_list(request):
    """
    List all Comments, or create a new Comment.
    """
    if request.method == 'GET':
        Comments = Comment.objects.all()
        serializer = CommentSerializer(Comments, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = CommentSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            # return the whole list, rather than the single comment
            Comments = Comment.objects.all()
            serializer = CommentSerializer(Comments, many=True)
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
def comment_details(request, pk, pk1):
    '''
    Change your comment for post pk, comment pk1. Input should be in the format:
    {"body": "right your comment" }
    '''
    try:  # Fectch the specific post
        post = Post.objects.get(pk=pk)
        #Update time_to_expire_field
        t = post.time_to_expire()  # get time to expire
        t = timezone.timedelta(seconds=int(t))
        serializer = PostSerializer(post)
        queryset_comment = Comment.objects.filter(
            post=serializer.data['id']
        )  # find all the comment related to a post
        queryset_preference = Preference.objects.filter(
            post=serializer.data['id']
        )  # find all the preference related to a post
        update_time(queryset_comment, t, CommentSerializer)
        update_time(queryset_preference, t, PreferenceSerializer)

    except Post.DoesNotExist:
        return Response('Post ' + str(pk) + ' Not found ')

    try:  # Fetch the specific preference
        comment = Comment.objects.get(pk=pk1)

    except Comment.DoesNotExist:
        return Response('Comment ' + str(pk1) + ' Not found ')

    if request.method == 'GET':
        #Update time_to_expire_field
        t = post.time_to_expire()  # get time to expire
        t = timezone.timedelta(seconds=int(t))
        serializer = PostSerializer(post)
        update_time(queryset_comment, t, CommentSerializer)
        update_time(queryset_preference, t, PreferenceSerializer)
        serializer_comm = CommentSerializer(comment)
        r = {
            'Post Title:': serializer.data['title'],
            'Post Owner:': serializer.data['owner'],
            'Post Status:': serializer.data['status'],
            'Comment Detail': serializer_comm.data,
        }
        return Response(r)
    elif request.method == 'PATCH':
        t = post.time_to_expire()  # get time to expire
        t = timezone.timedelta(seconds=int(t))
        serializer = PostSerializer(post)
        update_time(queryset_comment, t, CommentSerializer)
        update_time(queryset_preference, t, PreferenceSerializer)
        if serializer.data[
                'status'] == 'Live':  # Allow  preference modification only if the post is still Live
            serializer_comm = CommentSerializer(comment)
            data_mutable = request.data.copy()  #make the QueryDict mutable
            data_mutable[
                'owner'] = request.user.id  # set the current user as user
            if data_mutable['owner'] == serializer_comm.data[
                    'owner']:  # Allow modification only if the user is the owner of the preference
                serializer_comm_new = CommentSerializer(comment,
                                                        data=data_mutable,
                                                        partial=True)
                if serializer_comm_new.is_valid():
                    serializer_comm_new.save()
                    r = {
                        'Post Title:': serializer.data['title'],
                        'Post Owner:': serializer.data['owner'],
                        'Post Status:': serializer.data['status'],
                        'Comment Detail': serializer_comm_new.data,
                    }
                    return Response(r)
                return Response(serializer_comm_new.errors)
            else:  # User not owner of the comment
                return Response(
                    'Action denied, You are not the owner of this comment')
        else:  #Post expired
            return Response('Action denied, Post has expired')
    elif request.method == 'DELETE':

        #Update time to expire
        t = post.time_to_expire()  # get time to expire
        t = timezone.timedelta(seconds=int(t))
        serializer = PostSerializer(post)
        update_time(queryset_comment, t, CommentSerializer)
        update_time(queryset_preference, t, PreferenceSerializer)
        serializer_comm = CommentSerializer(comment)
        if serializer.data[
                'status'] == 'Live':  # Allow  preference modification only if the post is still Live
            if request.user.id == serializer_comm.data[
                    'owner']:  #he is the owner
                comment.delete()
                r = {
                    'message': 'Successfully Deleted',
                }
                return Response(r)
            else:
                return Response(
                    'Action can not performed! you are not owner of the comment. the owner Id is: '
                    + str(serializer_comm.data['owner']))
        else:
            return Response('Action denied, Post has expired')
class StudySerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='study-detail')
    user = UserSerializer(read_only=True)
    tags = serializers.SlugRelatedField(many=True,
                                        read_only=True,
                                        slug_field='name',
                                        allow_null=True)
    comment = CommentSerializer(many=True, read_only=True)

    class Meta:
        model = Study
        fields = [
            'id', 'url', 'user', 'title', 'body', 'tags', 'is_public',
            'comment', 'registered_date', 'last_edit_date'
        ]

    def __init__(self, *args, **kwargs):
        super(StudySerializer, self).__init__(*args, **kwargs)

    def create(self, validated_data):
        user = None
        request = self.context.get("request")

        if request and hasattr(request, "user"):
            user = request.user

        if request and hasattr(request, "review_cycle_in_minute"):
            study = Study.objects.create(
                user=user,
                title=validated_data['title'],
                body=validated_data['body'],
                is_public=validated_data['is_public'],
            )
        else:
            study = Study.objects.create(
                user=user,
                title=validated_data['title'],
                body=validated_data['body'],
                is_public=validated_data['is_public'],
            )

        for item in request.data['tags']:
            tag, created = Tag.objects.get_or_create(
                name=item, is_public=validated_data['is_public'])
            if created:
                study.tags.add(tag)

        return study

    def update(self, study, validated_data):
        study.title = validated_data.get('title', study.body)
        study.body = validated_data.get('body', study.body)
        study.is_public = validated_data.get('is_public', study.is_public)

        tags_to_update = self.initial_data.get('tags')

        temp = []
        for tag in tags_to_update:
            tag, created = Tag.objects.get_or_create(
                name=tag, is_public=validated_data['is_public'])
            temp.append(tag)

        study.tags.set(temp)

        return super(StudySerializer, self).update(study, validated_data)
Esempio n. 12
0
 def get_comments(self, obj):
     content_type = obj.get_content_type
     object_id = obj.id
     comments = Comment.objects.filter_by_instance(obj)
     return CommentSerializer(comments, many=True,
                              context=self.context).data
Esempio n. 13
0
 def comments(self, *args, **kwargs):
     """Get first level comments for entity"""
     page = self.paginate_queryset(self.entity_comments_queryset)
     serializer = CommentSerializer(page, many=True)
     return self.get_paginated_response(serializer.data)
Esempio n. 14
0
 def get_comments(self, obj):
     content_type = obj.get_content_type
     object_id = obj.id
     c_qs = Comment.objects.filter_by_instance(obj)
     comments = CommentSerializer(c_qs, many=True).data
     return comments
Esempio n. 15
0
def post_comment(request, next=None, using=None):
    """
    Post a comment.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``comments/preview.html``, will be rendered.
    """
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

    serializer = CommentSerializer(data)

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return CommentPostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
            escape(ctype))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
            (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
            (escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: %s" % \
            escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the comment
        '''
    if form.errors or preview:
        template_list = [
            # These first two exist for purely historical reasons.
            # Django v1.0 and v1.1 allowed the underscore format for
            # preview templates, so we have to preserve that format.
            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s_preview.html" % model._meta.app_label,
            # Now the usual directory based template hierarchy.
            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name),
            "comments/%s/preview.html" % model._meta.app_label,
            "comments/preview.html",
            ]
        return render_to_response(
            template_list, {
                "comment": form.data.get("comment", ""),
                "form": form,
                "next": data.get("next", next),
                },
            RequestContext(request, {})
        )
        '''


    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(
        sender=comment.__class__,
        comment=comment,
        request=request
    )

    for (receiver, response) in responses:
        if response == False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    '''
Esempio n. 16
0
 def comments(self, request, pk=None):
     return Response(CommentSerializer(Item.objects.get(pk=pk).comment_set.order_by("-date"), many=True).data)
Esempio n. 17
0
 def get_comments(self, obj):
     c_qs = Comment.objects.filter_by_instance(obj)
     comments = CommentSerializer(c_qs, many=True).data
     return comments
def post_comment(request, pk):
    '''
    Create a Comments to the post pk. Input should be in the format:
        {"body": "right your comment" }
    '''
    try:
        #Update time_to_expire_field
        post = Post.objects.get(pk=pk)
        t = post.time_to_expire()  # get time to expire
        t = timezone.timedelta(seconds=int(t))
        serializer = PostSerializer(post)
        queryset_comment = Comment.objects.filter(
            post=serializer.data['id']
        )  # find all the comment related to a post
        queryset_preference = Preference.objects.filter(
            post=serializer.data['id']
        )  # find all the preference related to a post
        update_time(queryset_comment, t, CommentSerializer)
        update_time(queryset_preference, t, PreferenceSerializer)
    except Post.DoesNotExist:
        return Response('Post ' + str(pk) + ' Not found ')
    if request.method == 'GET':
        #Update time_to_expire_field
        t = post.time_to_expire()  # get time to expire
        t = timezone.timedelta(seconds=int(t))
        serializer = PostSerializer(post)
        update_time(queryset_comment, t, CommentSerializer)
        update_time(queryset_preference, t, PreferenceSerializer)
        r = {
            'Number of comments:': len(serializer.data['comments']),
            'Data': serializer.data,
        }
        return Response(r)
    elif request.method == 'POST':
        #Update time_to_expire_field
        t = post.time_to_expire()  # get time to expire
        t = timezone.timedelta(seconds=int(t))
        serializer = PostSerializer(post)
        update_time(queryset_comment, t, CommentSerializer)
        update_time(queryset_preference, t, PreferenceSerializer)
        if serializer.data[
                'status'] == 'Live':  # Allow post preference only if the post is still Live
            # No limitation on the Ownership to comment
            #No limitation on the number of time you can comments the same post
            #Create Comment
            data_mutable = request.data.copy()  #make the QueryDict mutable
            data_mutable['post'] = serializer.data['id']
            data_mutable['time_to_expire'] = t
            data_mutable[
                'owner'] = request.user.id  # set the current user as user
            comm_serializer = CommentSerializer(data=data_mutable)
            if comm_serializer.is_valid():
                comm_serializer.save(
                    owner=request.user)  # set the current user as user
                r = {
                    'User ID': request.user.id,
                    'message': 'Successfully created comment',
                    'Data': comm_serializer.data,
                }
                return Response(r)
            return Response(comm_serializer.errors)

        else:  # Post is expired
            return Response('Action denied, Post has expired')
Esempio n. 19
0
 def __init__(self, *args, **kwargs):
     super(PostSerializer, self).__init__(*args, **kwargs)
     self.fields['comments'] = CommentSerializer(many=True,
                                                 read_only=True,
                                                 context=self.context)
Esempio n. 20
0
 def test_list_comments(self):
     url = reverse("post-comment", kwargs={"pk": self.post3.pk})
     response = self.client.get(url)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     serializer = CommentSerializer([self.comment2, self.comment1], many=True)
     self.assertEqual(response.data["results"], serializer.data)
Esempio n. 21
0
 def comments(self, request, *args, **kwargs):
     comment_list = Article.objects.get(pk=kwargs.get('pk')).comments.all()
     comment_serializer = CommentSerializer(comment_list, many=True)
     # json = JSONRenderer().render(comment_serializer.data)
     return Response(comment_serializer.data)
Esempio n. 22
0
 def get_comments(self, object):
     qs = Comment.objects.filter(
         post = object
     )
     return CommentSerializer(qs, many = True).data
Esempio n. 23
0
 def comments(self, request, pk=None):
     post = self.get_object()
     queryset = (
         post.comment_set.select_related('author').order_by('-created'))
     serializer = CommentSerializer(queryset, many=True)
     return Response(serializer.data)
Esempio n. 24
0
 def get(self, request, **kwargs):
     comments = self.get_comments(request.data.get('sort_by'))[
                int(kwargs['page']) * COMMENTS_PER_PAGE: (int(kwargs['page']) + 1) * COMMENTS_PER_PAGE]
     serializer = CommentSerializer(comments, many=True)
     return Response({'comment_tree': serializer.data}, template_name='comments/index.html')
Esempio n. 25
0
 def comments(self, request, pk=None):
     reviews = Comment.objects.filter(parent_id=pk)
     serializer = CommentSerializer(reviews, many=True)
     return Response(serializer.data)
Esempio n. 26
0
 def get(self, request, **kwargs):
     return Response(CommentSerializer(Comment.objects.get_comment(kwargs['id'])).data)
Esempio n. 27
0
 def get_comments(self, obj):
     serializer = CommentSerializer(obj.comments.all().order_by("-created"),
                                    many=True,
                                    context=self.context)
     return serializer.data
Esempio n. 28
0
class PostCommentSerializer(serializers.HyperlinkedModelSerializer):
    comments = CommentSerializer(many=True, read_only=True)

    class Meta:
        model = Post
        fields = ('url', 'title', 'body', 'profile', 'comments')