Exemplo n.º 1
0
def createProfileAPI(request):

    profile = Profile(account=request.user)

    serializer = ProfileSerializer(profile, 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)
Exemplo n.º 2
0
class CommentSerializer(serializers.ModelSerializer):
    author = ProfileSerializer(required=False)

    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')

    class Meta:
        model = Comment
        fields = (
            'id',
            'author',
            'body',
            'createdAt',
            'updatedAt',
        )

    def create(self, validated_data):
        article = self.context['article']
        author = self.context['author']

        return Comment.objects.create(author=author,
                                      article=article,
                                      **validated_data)

    def get_created_at(self, instance):
        return instance.created_at.isoformat()

    def get_updated_at(self, instance):
        return instance.updated_at.isoformat()
Exemplo n.º 3
0
def updateProfileAPI(request, id):

    try:
        profile = Profile.objects.get(id=id)
    except Profile.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if profile.account != request.user:
        return Response({'error': 'You don`t have permission to edit that!'},
                        status=status.HTTP_400_BAD_REQUEST)

    serializer = ProfileSerializer(profile, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 4
0
def userProfileAPI(request):
    user = request.user
    try:
        profile = Profile.objects.get(account=user)
    except Profile.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = ProfileSerializer(profile)
    return Response(serializer.data)
Exemplo n.º 5
0
class ArticleSerializer(serializers.ModelSerializer):
    author = ProfileSerializer(read_only=True)
    description = serializers.CharField(required=False)
    slug = serializers.SlugField(required=False)
    image_uri = serializers.SerializerMethodField()

    favorited = serializers.SerializerMethodField()
    favoritesCount = serializers.SerializerMethodField(
        method_name='get_favorites_count')

    tagList = TagRelatedField(many=True, required=False, source='tags')

    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')

    class Meta:
        model = Article
        fields = ('author', 'body', 'createdAt', 'description', 'image_uri',
                  'favorited', 'favoritesCount', 'slug', 'tagList', 'title',
                  'updatedAt', 'image')

    def create(self, validated_data):
        author = self.context.get('author', None)
        tags = []
        if self.context.get('tags'):
            tags = self.context.get('tags')
        article = Article.objects.create(author=author, **validated_data)
        for tag in tags:
            article.tags.add(tag)
        return article

    def get_created_at(self, instance):
        return instance.created_at.isoformat()

    def get_favorited(self, instance):
        request = self.context.get('request', None)

        if request is None:
            return False

        if not request.user.is_authenticated:
            return False

        return request.user.profile.has_favorited(instance)

    def get_favorites_count(self, instance):
        return instance.favorited_by.count()

    def get_updated_at(self, instance):
        return instance.updated_at.isoformat()

    def get_image_uri(self, instance):
        image_uri = ''
        if instance.image:
            image_uri = settings.BASE_URL + instance.image
        return image_uri
Exemplo n.º 6
0
class PostDetailSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(many=False, read_only=True)
    profile = ProfileSerializer(read_only=True, many=False)
    liked = serializers.SerializerMethodField()
    comments = CommentSerializer(read_only=True, many=True)

    class Meta:
        model = Post
        fields = [
            'id', 'title', 'body', 'author', 'profile', 'image', 'liked',
            'no_of_likes', 'no_of_comments', 'comments'
        ]

    def get_liked(self, obj):
        names = []
        for name in obj.liked.all():
            names.append(name.username)
        return names
Exemplo n.º 7
0
class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(max_length=128,
                                     min_length=8,
                                     write_only=True)

    profile = ProfileSerializer(write_only=True)

    bio = serializers.CharField(source='profile.bio', read_only=True)
    avatar = serializers.CharField(source='profile.avatar', read_only=True)
    birthday = serializers.CharField(source='profile.birthday', read_only=True)
    gender = serializers.CharField(source="profile.gender", read_only=True)

    class Meta:
        model = User
        fields = [
            'email', 'username', 'password', 'token', 'profile', 'bio',
            'avatar', 'birthday', 'gender'
        ]

        read_only_fields = ('token', )

    def update(self, instance, validated_data):
        print(validated_data)
        password = validated_data.pop('password', None)
        profile_data = validated_data.pop('profile', {})

        for (key, value) in validated_data.items():
            setattr(instance, key, value)

        if password is not None:
            instance.set_password(password)

        instance.save()

        for (key, value) in profile_data.items():

            if key == 'get_gender_display':
                setattr(instance.profile, 'gender', value)
            else:
                setattr(instance.profile, key, value)

        instance.profile.save()

        return instance
Exemplo n.º 8
0
class PostListSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(many=False, read_only=True)
    profile = ProfileSerializer(read_only=True, many=False)
    days_since_created = serializers.SerializerMethodField()
    created = serializers.SerializerMethodField()
    comments = CommentSerializer(read_only=True, many=True)
    user_has_liked = serializers.SerializerMethodField()
    user_is_post_author = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'title', 'slug', 'body', 'author', 'profile', 'image',
                  'no_of_likes', 'user_has_liked', 'no_of_comments',
                  'days_since_created', 'comments', 'created',
                  'user_is_post_author')

    def get_days_since_created(self, obj):
        return "{} days".format((now() - obj.created).days)

    def get_created(self, obj):
        return obj.created.strftime("%m/%d/%Y, %H:%M:%S")

    def get_liked(self, obj):
        names = []
        for name in obj.liked.all():
            names.append(name.username)
        return names

    def get_user_has_liked(self, obj):
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user
            return obj.liked.filter(pk=request.user.pk).exists()
        return None

    def get_user_is_post_author(self, obj):
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user
            return obj.author == user
Exemplo n.º 9
0
 def get_profile(self, obj, *args, **kwargs):
     p = self.context['request'].user.profile
     serializer = ProfileSerializer(obj.profiles.exclude(id=p.pk).get())
     return serializer.data