Пример #1
0
def unfollow_user(request, unfollow_username):
    unfollow_user = User.objects.filter(username=unfollow_username).first()
    if request.user.is_authenticated and (request.user != unfollow_user):
        unfollow_user_profile = Profile.objects.filter(
            user=unfollow_user).first()
        for item in unfollow_user_profile.followers:
            if(item["id"] == request.user.id):
                unfollow_user_profile.followers.remove(item)
            unfollow_user_profile.save()
        request_user_profile = get_object_or_404(
            Profile, user=request.user)
        # Removing requested user from user followers list
        
        

        # Removing unfollow user from requested user following list
        for item in request_user_profile.following:
            if(item["id"] == unfollow_user.id):
                request_user_profile.following.remove(item)
            request_user_profile.save()
        unfollow_user_profile = ProfileSerializer(
            unfollow_user_profile, many=False)
        request_user_profile.save()
        request_user_profile = ProfileSerializer(
            request_user_profile, many=False)
        return Response(request_user_profile.data, status=HTTP_200_OK)
    else:
        return Response({"error": "Authentication credential not found"}, status=HTTP_401_UNAUTHORIZED)
Пример #2
0
	def get_other_profile(self, obj):
		my_user = self.context['request'].user

		if my_user == obj.profile_1.user:
			return ProfileSerializer(obj.profile_2).data

		return ProfileSerializer(obj.profile_1).data
Пример #3
0
class ThreadSerializer(WritableNestedModelSerializer):
	profile_1 = ProfileSerializer()
	profile_2 = ProfileSerializer()
	recent_message = serializers.SerializerMethodField()
	
	def get_recent_message(self, obj):
		return MessageSerializer(Message.objects.filter(thread__id=obj.id).order_by('timestamp').last()).data

	class Meta:
		model = Thread
		fields = ('id', 'profile_1', 'profile_2', 'recent_message', )
		read_only_fields = ('id', 'profile_1', 'profile_2', 'recent_message', )
Пример #4
0
def snippet_list(request):
    #List all code snippets, or create a new snippet.
    if request.method == 'GET':
        profile = Profile.objects.all()
        serializer = ProfileSerializer(profile, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ProfileSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Пример #5
0
def follow_user(request, follow_username):
    follow_user = get_object_or_404(User, username=follow_username)
    if request.user.is_authenticated and (request.user != follow_user):
        follow_user_profile = Profile.objects.filter(
            user=follow_user).first()
        request_user_profile = get_object_or_404(
            Profile, user=request.user)
        if any(x["id"] == request.user.id for x in follow_user_profile.followers):
            unfollow_user(request, follow_username) 
            return Response({"data": "User unfollowed", "status": True, "action": "USER_UNFOLLOWED"}, status=HTTP_200_OK)
        if follow_user_profile.is_private == False:
            # Adding requesting user to the follower list
            follow_user_profile.followers.append(
                {"username": request.user.username, "id": request.user.id, "profile_picture":request_user_profile.profile_picture.url if request_user_profile.profile_picture else None})
            follow_user_profile.save()

            # Adding followed user to the following list
            request_user_profile.following.append(
                {"username": follow_user.username, "id": follow_user.id, "profile_picture": follow_user_profile.profile_picture.url if follow_user_profile.profile_picture else None})
            request_user_profile.save()
            request_user_profile = ProfileSerializer(
                request_user_profile, many=False)
            return Response({"data": "User followed", "status": True, "action": "USER_FOLLOWED"}, status=HTTP_200_OK)
        else:
            if any(x["id"] == request.user.id for x in follow_user_profile.followers):
                return Response({"data": "Follow request sent", "status": True, "action": "REQUEST_SENT"}, status=HTTP_200_OK)
            else:
                follow_user_profile.follow_request.append(
                    {"username": request.user.username, "id": request.user.id, "profile_picture":request_user_profile.profile_picture.url if request_user_profile.profile_picture else None}
                )
                follow_user_profile.save()
                return Response({"data": "Follow request sent", "status": True, "action": "REQUEST_SENT"}, status=HTTP_200_OK)
    else:
        return Response({"data": "Authentication credential not found", "status": False, "action": "NOT_FOUND"}, status=HTTP_401_UNAUTHORIZED)
Пример #6
0
    def post(self, request):
        if User.objects.filter(email=request.data['email']).exists():
            errors = {'errors': {'email': 'Email already exists.'}}
            return Response(errors, status=status.HTTP_400_BAD_REQUEST)

        username = lower(request.data['first_name']) + lower(
            request.data['last_name'])
        user = User.objects.create(
            username=username,
            first_name=request.data['first_name'],
            # add lastname for the user only if it is a string, otherwise add empty string
            last_name=request.data['last_name']
            if not request.data['last_name'] == "1" else "",
            email=request.data['email'],
        )
        # save hashed password value
        user.set_password(request.data['password'])
        user.save()

        settings = UserSettings.objects.create()
        settings.save()

        profile = Profile.objects.create(
            user=user,
            settings=settings,
        )
        profile.save()

        serialized = ProfileSerializer(profile)
        if serialized:
            return Response(serialized.data, status=status.HTTP_201_CREATED)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)
Пример #7
0
def home(request):
    if request.user.is_authenticated:
        user_profile = get_object_or_404(Profile, user=request.user)
        following_list = []
        for following in user_profile.following:
            following_list.append(following["username"])
        post_list = []
        for user in following_list:
            u = get_object_or_404(User, username=user)
            posts = Post.objects.filter(user=u)
            for post in posts:
                profile = get_object_or_404(Profile, user=post.user)
                user_profile = ProfileSerializer(profile, many=False)
                is_current_user_liked = False
                if any(x["id"] == request.user.id for x in post.likes):
                    is_current_user_liked = True
                post = PostSerializer(post, many=False)
                post_list.append({
                    "post": post.data,
                    "is_current_user_liked": is_current_user_liked,
                    "profile": user_profile.data
                })
            post_list = sorted(post_list,
                               key=lambda x: x["post"]["timestamp"],
                               reverse=True)
        return Response(post_list, status=status.HTTP_200_OK)
    else:
        return Response({"error": "Authentication credential not provided"},
                        status=status.HTTP_401_UNAUTHORIZED)
Пример #8
0
def getToken(request):
    if request.data.get("username") and request.data.get("password"):
        user = get_object_or_404(User, username=request.data.get("username"))
        token, created = Token.objects.get_or_create(user=user)
        user_profile = get_object_or_404(Profile, user=user)
        user_profile = ProfileSerializer(user_profile, many=False)
        user = UserSerializer(user, many=False)
        return Response(
            {
                "data": {
                    "user_profile": user_profile.data,
                    "user_data": user.data,
                    "token": token.key
                },
                "status": True,
                "message": "Loggin successfully"
            },
            status=HTTP_201_CREATED)

    else:
        return Response(
            {
                "message": "Username or Password is empty",
                "data": {},
                "status": False
            },
            status=HTTP_200_OK)
Пример #9
0
def create_user(request):
    try:
        data = JSONParser().parse(request)
        data['username'] = data['email']
        if User.objects.filter(username=data['username']).exists():
            return JsonResponse({'message': 'User already exists'}, status=200)
        serializer = SignupSerializer(data=data)
        profile_serializer = ProfileSerializer(data=data)
        if serializer.is_valid():
            user = serializer.save()
            data['user_id'] = user.id
            if profile_serializer.is_valid():
                profile = profile_serializer.save()
                guest_role = Roles.objects.get(role_name='guest')
                user_with_role = UserRoles.objects.create(user=user,
                                                          role=guest_role)
                token = Token.objects.create(user=user)
                response = {
                    'token': token.key,
                    'role': guest_role.role_name,
                    'phone_number': profile.phone_number,
                    'gender': profile.gender
                }
                return JsonResponse(response, status=200)
            return JsonResponse(profile_serializer.errors, status=400)
        return JsonResponse(serializer.errors, status=400)
    except BaseException as error:
        print(error)
        response = {'error': "some error occurred while signing up"}
        return JsonResponse(response, status=400)
Пример #10
0
 def get(self, request, pk, format=None):
     """
     API endpoint that list all profiles.
     ---
     Body example:
     ```
     [
         {
             "id": 1,
             "hours": 5,
             "abilities": [
                 {
                     "id": 1,
                     "name": "Gamificacao"
                 }
             ],
             "user": 1,
             "phone": 10,
             "photo": null,
             "coins": 0
         }
     ]
     ```
     """
     profile = self.get_object(pk)
     serializer = ProfileSerializer(profile)
     return Response(serializer.data)
Пример #11
0
def generate_profile(token, user=None, request=None) -> dict:
    profile = ProfileSerializer(user.profile, context={"request": request}).data
    token = {
        "token": token
    }
    profile["user"].update(token)
    return profile
Пример #12
0
class PostSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True)
    comments = CommentSerializer(many=True)

    class Meta:
        model = Post
        fields = ('id', 'profile', 'photo', 'likes', 'description', 'comments')
Пример #13
0
 def put(self, request):
     profile = Profile.objects.get(user=self.request.user)
     serializer = ProfileSerializer(instance=profile, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors)
Пример #14
0
def update_profile(request):
    if request.user.is_authenticated:
        user = get_object_or_404(User, id=request.user.id)
        if user:
            user_profile = get_object_or_404(Profile, user=request.user)
            user_profile.profile_picture = request.FILES.get(
                "profile_picture") if request.FILES.get(
                    "profile_picture") else user_profile.profile_picture
            user_profile.bio = request.data.get("bio") if request.data.get(
                "bio") else user_profile.bio
            user_profile.website = request.data.get(
                "website") if request.data.get(
                    "website") else user_profile.website
            user_profile.is_private = request.data.get(
                "is_private") if request.data.get(
                    "is_private") else user_profile.is_private
            user_profile.save()
            user.first_name = request.data.get(
                "first_name") if request.data.get(
                    "first_name") else user.first_name
            user.last_name = request.data.get("last_name") if request.data.get(
                "last_name") else user.last_name
            user.email = request.data.get("email") if request.data.get(
                "email") else user.email
            user.save()
            user_profile = ProfileSerializer(user_profile, many=False)
            return Response(user_profile.data)
        else:
            return Response({"message": "Account not found"},
                            status=HTTP_404_NOT_FOUND)
    else:
        return Response({"error": "Authentication details not provided"},
                        status=HTTP_401_UNAUTHORIZED)
Пример #15
0
def create_profile(
    strategy, backend, user=None, flow=None, current_partial=None, *args, **kwargs
):  # pylint: disable=too-many-arguments,unused-argument
    """
    Creates a new profile for the user
    Args:
        strategy (social_django.strategy.DjangoStrategy): the strategy used to authenticate
        backend (social_core.backends.base.BaseAuth): the backend being used to authenticate
        user (User): the current user
        flow (str): the type of flow (login or register)
        current_partial (Partial): the partial for the step in the pipeline

    Raises:
        RequireProfileException: if the profile data is missing or invalid
    """
    if backend.name != EmailAuth.name or user.profile.is_complete:
        return {}

    data = strategy.request_data().copy()

    serializer = ProfileSerializer(instance=user.profile, data=data)
    if not serializer.is_valid():
        raise RequireProfileException(
            backend, current_partial, errors=serializer.errors
        )
    serializer.save()
    sync_hubspot_user(user)
    return {}
Пример #16
0
def profile_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        profiles = Profile.objects.all()
        serializer = ProfileSerializer(profiles, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ProfileSerializer(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)
Пример #17
0
class PostSerializer(serializers.ModelSerializer):
    user_name = serializers.ReadOnlyField(source='user.username')
    profile = ProfileSerializer(read_only=True)
    profileId = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Profile.objects.all(), source='profile')
    comments = CommentSerializer(many=True, read_only=True, source='comment_set')
    activity = ActivitySerializer(read_only=True)
    activityId = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Activity.objects.all(), source='activity')
    # activities = ActivitySerializer(many=True, read_only=True, source='activity_set')
    # interest = InterestSerializer(many=True, read_only=True, source='interest_set')
    # interest = InterestSerializer(read_only=True)
    # interestsId = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Interest.objects.all(), source='interest')
    # user = UserSerializer(no_required=True)
    # user = UserSerializer(source='user.username')
    # user = serializers.PrimaryKeyRelatedField(write_only=True, queryset=User.objects.all(), required=True)
      # profile = serializers.ReadOnlyField(source='s')
#     user = serializers.PrimaryKeyRelatedField(
#     many=False,
#     queryset=User.objects.all(), source='user.username',
   
# ) user = UserSerializer()

    # def create(self, validated_data):
    #     profile_data = validated_data.pop('user')
    #     user = User.objects.create(**profile_data)
    #     # for profile_data in profile_data:
    #     Post.objects.create(user=user, **validated_data)
    #     return user

    class Meta:
        model = Post
        fields = '__all__'
Пример #18
0
class CommentSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True)
    profileId = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Profile.objects.all(), source='profile')

    class Meta:
        model = Comment
        fields = '__all__'
Пример #19
0
class MinimalPostSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='get_uri_key')
    author = ProfileSerializer(read_only=True, source='get_profile')

    class Meta:
        model = Post
        fields = ('id', 'author', 'text',)
Пример #20
0
    def post(self, request):
        """
        accepts a JSON request body in the following format:
        {
          "input": <message to send to watson>,
          "config": {
            "inputFormat": "text" | "speech",
            "outputAsSpeech": <boolean>
          }
        }
        """
        message = request.data.get("input", request.data.get("inputText"))
        config = request.data.get("config", {})
        datasets = request.data.get("datasets", [])
        try:
            profile = request.user.profile
        except Profile.DoesNotExist:
            profile = ProfileSerializer(data={"user": request.user}).save()

        assistant_api = AssistantAPI(profile, datasets)

        if config.get("inputFormat") == "speech":
            mime_type = config.get("mimeType")
            message_text = assistant_api.speech_to_text(message, mime_type)
        else:
            message_text = message

        data = assistant_api.message(message_text)
        data["input_text"] = message_text
        if config.get("outputAsSpeech"):
            data["speech"] = assistant_api.text_to_speech(data["text"])

        return Response(json.dumps(data), status=status.HTTP_200_OK)
Пример #21
0
    def post(self, request, format=None):
        profile = request.user.profile
        profile.profile = request.data['profile']
        profile.save()

        serializer = ProfileSerializer(profile)
        return Response(serializer.data)
Пример #22
0
 def profile(self, request ):
     user = request.user
     profile = Profile.objects.get(user=user)
     partial = request.method == 'PATCH'
     serializer = ProfileSerializer(profile, data=request.data , partial =partial)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return Response(serializer.data , status=200)
Пример #23
0
class PostSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True)
    comments = CommentSerializer(many=True, read_only=True)

    class Meta:
        model = Post
        fields = ("pk", "profile", "title", "body", "image", "published_date",
                  "likes", "comments")
Пример #24
0
class CommentSerializer(serializers.ModelSerializer):
    author = ProfileSerializer(read_only=True, source='author.profile')
    image = serializers.ImageField(allow_null=True, max_length=100, required=False, validators=[FileSizeValidator(0.5)])

    class Meta:
        model = Comment
        fields = ('id', 'author', 'created', 'text', 'image',)
        read_only_fields = ('created',)
Пример #25
0
class QuestionListSerializer(serializers.ModelSerializer):
    author = ProfileSerializer()
    tags = TagSerializer(many=True)
    answer_count = serializers.IntegerField()

    class Meta:
        model = models.Post
        fields = ('code', 'title', 'rating', 'tags', 'created_at', 'answer_count', 'author')
Пример #26
0
def user_detail(request, username):
    user = get_object_or_404(User, username=username)
    user_profile = Profile.objects.filter(user=user.id).first()
    if user_profile.is_private:
        if request.user.is_authenticated:
            is_followed = False
            for item in user_profile.followers:
                if (item["id"] == request.user.id):
                    is_followed = True
            if is_followed:
                follower_count = len(user_profile.followers)
                following_count = len(user_profile.following)
                posts = Post.objects.filter(user=user)
                posts = PostSerializer(posts, many=True)
                user_profile = ProfileSerializer(user_profile, many=False)
                return Response(
                    {
                        "data": user_profile.data,
                        "posts": posts.data,
                        "post_count": len(posts.data),
                        "follower_count": follower_count,
                        "following_count": following_count
                    },
                    status=HTTP_200_OK)
            else:
                user = UserSerializer(user, many=False)
                return Response({"data": user.data})
        else:
            user = UserSerializer(user, many=False)
            return Response({"data": user.data})
    else:
        follower_count = len(user_profile.followers)
        following_count = len(user_profile.following)
        posts = Post.objects.filter(user=user)
        posts = PostSerializer(posts, many=True)
        user_profile = ProfileSerializer(user_profile, many=False)
        return Response(
            {
                "data": user_profile.data,
                "posts": posts.data,
                "post_count": len(posts.data),
                "follower_count": follower_count,
                "following_count": following_count
            },
            status=HTTP_200_OK)
Пример #27
0
    def get(self, request, format=None):
        """
        Get all profiles

        ---
        """
        profiles = Profile.objects.all()
        serializer = ProfileSerializer(profiles, many=True)
        return Response(serializer.data)
Пример #28
0
class LikeSerializer(serializers.ModelSerializer):

    user = ProfileSerializer()
    session = GroupSessionSerializer()
    username = serializers.Field(source='user.user.username')

    class Meta:
        model = Like
        fields = ('id', 'username', 'session', 'created', 'modified')
Пример #29
0
def create_profile(sender, instance, created, *args, **kwargs):
    if not created:
        return

    profile_serializer = ProfileSerializer(data={"user": instance.id})
    if profile_serializer.is_valid():
        profile_serializer.save()
    else:
        print(profile_serializer.errors)
Пример #30
0
    def test_to_representation(self):
        profile = ProfileFactory()

        data = ProfileSerializer(profile).data

        assert data["username"] == profile.user.username
        assert data["last_name"] == profile.user.last_name
        assert data["first_name"] == profile.user.first_name
        assert data["description"] == profile.description