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)
def comment(self, request, *args, **kwargs): """Create comment for entity""" pk = self.get_object().pk serializer = CommentSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(entity_type=self.entity_type.value, entity_id=pk) return Response(serializer.data, status=status.HTTP_201_CREATED)
def add_comment( self, request: Request, pk=Optional[str] ) -> Response: serializer = CommentSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(post=self.get_object(), author=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED)
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)
def comment_create(request): """ Create a new comment. """ if request.method == 'POST': request_data = request.data request_data.update({ 'user': request.user.id, }) serializer = CommentSerializer(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)
def post(self, request): """ Adding new comments for users. :param request: HTTP request with user and his comment info inside .data. :return: HTTP response. With serialized JSON data of updated comments tree and Http status code 201 or serializer validation's errors with messages and Http status 400. """ comment_serializer = CommentSerializer(data=request.data, context={'request': request}) if comment_serializer.is_valid(raise_exception=True): comment_serializer.save() return Response(data=comment_serializer.data, status=status.HTTP_201_CREATED) return Response(data=comment_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def patch(self, request, message_id): """Edit the message for an existing comment. Args: request: Request object. message_id (int): id of comment id. Returns: dict: details of the updated comment. Example: { "post_id": 1, "author_id": 1, "message": "Updated Message", "created_on": "2021-04-10T12:54:26.436566Z", "updated_on": "2021-04-10T15:08:19.840550Z", "parent_id": 1, "last_child_id": 3, "id": 2 } """ # Get the message to be updated and the request user. message = request.data.get("message") user = request.user # Fetch the comment to be updated. comment = Comment.objects.filter(id=message_id, author=user).first() # If comment there is no matching comment, return status 404. if not comment: return Response(status=status.HTTP_404_NOT_FOUND) # Initialize the serializer class. serializer_instance = CommentSerializer(comment, data={"message": message}, partial=True) # If the payload to be updated has error, then return the errors. if not serializer_instance.is_valid(): return serializer_instance.errors # Update the comment with the updated message. serializer_instance.save() return Response(data=serializer_instance.data, status=status.HTTP_200_OK)
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 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) '''
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')
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')