Exemple #1
0
 def post(self,request):
     serializer = UserProfileSerializer(data=request.data)
     if serializer.is_valid():
             message = 'data saved'
             serializer.save()
             return Response({'message':message})
     else:
         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
class PostSerializer(serializers.ModelSerializer):
    posted_by = UserProfileSerializer(read_only=True)
    liked_by = UserProfileSerializer(many=True, read_only=True)
    comments = SubCommentSerializer(many=True, read_only=True)
    shared_by = UserProfileSerializer(many=True, read_only=True)

    class Meta:
        model = Post
        fields = '__all__'
        read_only_fields = ['posted_by', 'liked_by', 'comments', 'shared_by']
Exemple #3
0
class UserSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    groups = serializers.SlugRelatedField(many=True,
                                          queryset=Group.objects.all(),
                                          slug_field='name')
    profile = UserProfileSerializer(allow_null=True)

    # def to_representation(self, value):
    #     data = super().to_representation(value)
    #     data['profile'] = {}
    #     return data

    class Meta:
        model = User
        # fields = "__all__"
        fields = [
            'id', 'username', 'groups', 'last_login', 'is_superuser', 'email',
            'is_staff', 'is_active', 'profile'
        ]
        extra_kwargs = {
            'password': {
                'allow_null': True,
                'allow_blank': True
            }
        }  # 指定序列化字段属性
Exemple #4
0
class CommentSerializer(serializers.ModelSerializer):
    user_profile = UserProfileSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = ['id', 'content', 'user_profile']
        read_only_fields = ['user_profile']
Exemple #5
0
    def get(request):
        """
        List profiles
        """

        profiles = UserProfile.objects.all()
        return Response(UserProfileSerializer(profiles, many=True).data)
Exemple #6
0
    def get(self, request, format=None):
        """
        """
        data = request.data
        user_profile = request.user.userprofile

        serializer = UserProfileSerializer(user_profile)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #7
0
    def patch(self, request, format=None):
        """
        """
        data = request.data
        user_profile = request.user.userprofile

        if data.get("new_password") and data.get("old_password"):
            if len(data.get("new_password")) < 8:
                return Response(error_conf.INSUFFICIENT_PASSWORD_LENGTH,
                                status=status.HTTP_412_PRECONDITION_FAILED)
            else:
                valid = request.user.check_password(data.get("old_password"))
                if vald:
                    request.user.set_password(data.get("new_password"))
                else:
                    return Response(error_conf.INVALID_PASSWORD,
                                    status=status.HTTP_412_PRECONDITION_FAILED)

        if data.get('user'):
            user = request.user
            user.first_name = data.get('user', {}).get('first_name')
            user.save()
            del data['user']

        serializer = UserProfileSerializer(user_profile,
                                           data=data,
                                           partial=True)
        if serializer.is_valid():
            serializer.save()
            serializer = UserProfileSerializer(user_profile)
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #8
0
def user_profile_element(request, pk):
    try:
        user_profile = UserProfile.objects.get(pk=pk)
    except UserProfile.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserProfileSerializer(user_profile)
        return Response(serializer.data)
Exemple #9
0
    def post(self, request, **kwargs):
        """
        POST request to change user profile fields
        """
        try:
            data = request.DATA
            user = User.objects.get(id=int(data.get('id')))
            profile = UserProfile.objects.get(user=user)

            profile_data = {
                'phone': data.get('phone'),
                'user': user.id,
                'location': profile.location,
            }

            user.first_name = data.get('first_name')
            user.last_name = data.get('last_name')

            if data.get('photo'):
                profile_data['photo'] = data.get('photo')
                profile_serializer = UserProfileSerializer(profile,
                                                           data=profile_data)

                if profile_serializer.is_valid():
                    # Deletes first its previous image to save server storage space
                    if profile.photo:
                        profile.photo.delete(False)

                    user.save()
                    profile_serializer.save()
                else:
                    return Response(profile_serializer.errors,
                                    status=status.HTTP_400_BAD_REQUEST)
            else:
                user.save()

                profile.phone = data.get('phone')
                profile.save()

            return Response("Success", status=status.HTTP_200_OK)
        except Exception as e:
            return Response("Error: {}".format(e),
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #10
0
    def post(self, request, format=None):
        """
        POST request to create a new User and UserProfile
        """

        data = request.DATA
        serializer = UserSerializer(data=data)

        if serializer.is_valid():
            user = serializer.save()

            # Create APNSDevice instance for current user
            device_token = data.get('device_token')

            profile = UserProfile.objects.get(user=user)

            if device_token != "none":
                apns_device, created = APNSDevice.objects.get_or_create(
                    registration_id=device_token)
                apns_device.user = user

                apns_device.save()

            if data.get('photo'):
                profile_data = {
                    'user': user.id,
                    'location': "",
                    'photo': data.get('photo')
                }
                profile_serializer = UserProfileSerializer(profile,
                                                           data=profile_data)

                if profile_serializer.is_valid():
                    profile_serializer.save()
                else:
                    return Response(profile_serializer.errors,
                                    status=status.HTTP_400_BAD_REQUEST)

            return Response(None, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #11
0
def serialize_activities(activities, request):
    """Serializes the objects based on a property "activity_object_serializer_class"""
    for activity in activities:
        activity['object'] = get_serialized_object_or_str(activity['object'])
        user = activity['actor']
        activity['actor'] = UserSerializer(activity['actor'],
                                           context={
                                               'request': request
                                           }).data
        user_profile = UserProfile.objects.get(user=user)
        activity['profile'] = UserProfileSerializer(user_profile).data
    return activities
Exemple #12
0
def user_autocomplete(request):
    """Very basic function that expects a 'q' url param and returns a list of users whose first name
    starts with whatever is in q.  This is case insensitive
    """
    query = request.GET.get('q')
    print "in user_autocomplete.  Query is: ", query
    if query:
        query_set = UserProfile.objects.filter(user__first_name__istartswith=query)
        # import pdb; pdb.set_trace()
        return Response(UserProfileSerializer(query_set, many=True, context={'request': request}).data, status=status.HTTP_200_OK)
    return Response({'error': 'Cannot find any users whose first name start with that query'},
                    status=status.HTTP_404_NOT_FOUND)
Exemple #13
0
class UserSerializer(serializers.ModelSerializer):
    """ Responsible for updating user fields and
        retrieving a single user.
    """

    # give the model serializer a password field, so it
    # would not be refering to the required password field of the model
    # therefore update() will not require password field.
    password = serializers.CharField(min_length=8,
                                     max_length=128,
                                     write_only=True)

    # instead of returning the id of the OneToOneField UserProfile,
    # this allows retrieval of the entire UserProfile object.
    profile = UserProfileSerializer()

    class Meta:
        model = User
        fields = ('id', 'email', 'name', 'password', 'profile')

        read_only_fields = (
            'id',
            'email',
        )

    def update(self, instance, validated_data):
        """ Provides logic for updating/partially updating the user.
            Instance refers to the user being updated.
            Example use:
            user = User.objects.get(pk=id)
            serializer = UserSerializer(user, data=request.data, partial=True)
            .... serializer.save() after validation
        """

        # Remove and retrieve password from validated_data dictionary
        # pop() returns None if the password is not set
        password = validated_data.pop('password', None)

        # if password is provided in the validated data,
        # set the encrypted password
        if password is not None:
            instance.set_password(password)

        # set all other properties provided for the user
        # setattr(instance, key, value) works the same way as instance.key=value
        # where the key is the name of the property of the instance.
        for (key, value) in validated_data.items():
            setattr(instance, key, value)

        # save changes to the database's table for the User model.
        instance.save()
        return instance
Exemple #14
0
class CustomSerializer(ModelSerializer):
    profile = UserProfileSerializer(read_only=True, required=False)

    class Meta:
        model = UserModel
        fields = ['id', 'email', 'password', 'created', 'updated', 'profile']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        user = UserModel.objects.create_user(**validated_data)
        return user
Exemple #15
0
    def get(self, request, format=None):
        """Retruns a list of APIViews features."""

        an_apiview = [
            'Uses HTTP methods as fucntion (get, post, patch, put, delete)',
            'It is similar to a traditional Django view',
            'Gives you the most of the control over your logic',
            'Is mapped manually to URLs'
        ]
        user_profiles = UserProfile.objects.all()
        serializer = UserProfileSerializer(user_profiles, many=True)
        #The response must be as dictionary which will be shown in json as response
        return Response({'message': 'Hello!', 'an_apiview': an_apiview, 'data':serializer.data})
Exemple #16
0
 def post(self, request):
     data = dict(request.data.items())
     data['user'] = request.user.id
     if 'image' in request.data and 'image' is not None:
         serializer = UserPostSerializer(data=data)
         if serializer.is_valid():
             serializer.save()
             data['image'] = serializer.data['id']
     instance = UserProfile.objects.get(id=data['user'])
     serializer = UserProfileSerializer(data=data, instance=instance)
     if serializer.is_valid():
         serializer.save()
         return Response({'status': 'success'}, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #17
0
class IdeaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Idea
        fields = [
            'id', 'title', 'creator', 'description', 'block', 'functions',
            'departments', 'technologies'
        ]

    creator = UserProfileSerializer()
    functions = FunctionSerializer(
        many=True
    )  # serializers.PrimaryKeyRelatedField(queryset=Function.objects.all(), many=True)
    departments = DepartmentSerializer(
        many=True
    )  # serializers.PrimaryKeyRelatedField(queryset=Department.objects.all(), many=True)
    technologies = TechnologySerializer(
        many=True
    )  # serializers.PrimaryKeyRelatedField(queryset=Technology.objects.all(), many=True)
Exemple #18
0
def user_profile_collection(request):
    if request.method == 'GET':
        user_profiles = UserProfile.objects.all()
        serializer = UserProfileSerializer(user_profiles, many=True)
        return Response(serializer.data)