def set_password(self, request, pk=None):
     user = self.get_object()
     serializer = AccountSerializer(data=request.data)
     if serializer.is_valid():
         user.set_password(serializer.data['password'])
         user.save()
         return Response({'status': 'password set'})
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
示例#2
0
class PostSerializer(serializers.ModelSerializer):
    author = AccountSerializer(required=False, read_only=True)

    class Meta:
        model = Post

        fields = ('id', 'author', 'content', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')

        def get_validation_exclusions(self, *args, **kwargs):
            exclusions = super(PostSerializer,
                               self).get_validation_exclusions()

            return exclusions + ['author']
示例#3
0
class ReservationSerializer(serializers.ModelSerializer):
    account = AccountSerializer(read_only=False, required=False)
    lesson = LessonSerializer(read_only=False, required=False)

    class Meta:
        model = Reservation
        fields = ('id', 'account', 'lesson', 'nb_personnes', 'checked_present', 'nb_present', 'confirmed', 'created', 'updated')

        def create(self, validated_data):
            return Reservation.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.date = validated_data.get('date', instance.date)
            instance.save()
            return instance
示例#4
0
class MessageSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    message = serializers.CharField(required=False)

    class Meta:
        model = Message
        fields = ('id', 'room', 'message', 'timestamp', 'author', 'checked',
                  'encrypted')
        read_only_fields = ('id', )

    def create(self, validated_data
               ):  # update parent room's last message time for sorting
        instance = super(MessageSerializer, self).create(validated_data)
        instance.room.update_last_msg_time(instance.timestamp)
        return instance
示例#5
0
class WordSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)

    class Meta:
        model = Word

        fields = ('id', 'name', 'translation', 'comment', 'favorite',
                  'wordType', 'author', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')
        validators = []  # Remove a default "unique together" constraint.

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(WordSerializer, self).get_validation_exclusions()

        return exclusions + ['author']
示例#6
0
class PudSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)

    class Meta:
        model = Pud

        fields = ('id', 'author', 'content', 'notification', 'priority', 'priority_int', 'duration', 'is_completed',
                  'repeat', 'repeat_int', 'need_repeat', 'notify_when', 'assignedToPost', 'firstAssignedWeek',
                  'created_at', 'updated_at', 'expiry_time', 'expiry_day', 'expires', 'escalate', 'expiry')
        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(PudSerializer, self).get_validation_exclusions()

        return exclusions + ['author']
 def create(self, request):
     serializer = self.serializer_class(data=request.data)
     if serializer.is_valid():
         if serializer.checkPassword(serializer.validated_data):
             account = Account.objects.create_user(
                 **serializer.validated_data)
             serialized = AccountSerializer(account)
             return Response({'user': serialized.data},
                             status=status.HTTP_201_CREATED)
     return Response(
         {
             'status': 'Bad request',
             'message': 'Account could not be created with received data.'
         },
         status=status.HTTP_400_BAD_REQUEST)
示例#8
0
class CommentSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    comment_images = DataImageSerializer(many=True,
                                         read_only=True,
                                         required=False)

    class Meta:
        model = Comment
        fields = ('id', 'author', 'parent_post', 'content', 'created_at',
                  'updated_at', 'comment_images')
        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(CommentSerializer, self).get_validation_exclusions()
        return exclusions + ['author']  #+ ['parent_post']
示例#9
0
class PollSerializer(serializers.ModelSerializer):
    """ Serializer for Poll model.
    """
    author = AccountSerializer(read_only=True, required=False)
    options = OptionSerializer(read_only=True, many=True)

    class Meta:
        model = Poll
        fields = ('id', 'author', 'question', 'options', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(PollSerializer, self).get_validation_exclusions()

        return exclusions + ['author']
示例#10
0
class PinSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    board = BoardSerializer(read_only=True, required=False)

    class Meta:
        model = Pin

        fields = ('id', 'author', 'board', 'title', 'content', 'image',
                  'latitude', 'longitude', 'link', 'location', 'mapsURL',
                  'usPOC', 'hnPOC', 'mgrs', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')

        def get_validation_exclusions(self, *args, **kwargs):
            exclusions = super(PinSerializer, self).get_validation_exclusions()

            return exclusions + ['author']
示例#11
0
class PostSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    country = CountrySerializer(read_only=True, required=False)

    class Meta:
        model = Post

        fields = ('id', 'author', 'country', 'name', 'tagline', 'votes_count',
                  'comments_count', 'redirect_url', 'discussion_url', 'day',
                  'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(PostSerializer, self).get_validation_exclusions()

        return exclusions + ['author']
示例#12
0
class BoardSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)

    class Meta:
        model = Board

        fields = ('id', 'author', 'title', 'description', 'created_at',
                  'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')

        def create(self, validated_data):
            return Board.objects.create(**validated_data)

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(BoardSerializer, self).get_validation_exclusions()

        return exclusions + ['author']
示例#13
0
class ProjectSerializer(serializers.ModelSerializer):
    """ Serialize Project for use with RESTful API.
        When serializing, we want to include all of the author's information
            (a nested relationship). Set to read_only so there are no updates
            to the Account, and required=False so we can set the author
            automatically (this means we also need to add 'author' to
            the validation exclusions)
        TODO: only serialize essential Account data; unnecessary to send all.
    """
    class Meta:
        """ Meta class configuring serializer. """
        model = Project
        fields = ('id', 'author', 'title', 'description', 'created_at',
                  'updated_at', 'majors', 'tags')
        read_only_fields = ('id', 'created_at', 'updated_at')

    author = AccountSerializer(read_only=True, required=False)
    majors = serializers.SlugRelatedField(many=True,
                                          slug_field='title',
                                          queryset=Major.objects.all())
    tags = serializers.SlugRelatedField(many=True,
                                        slug_field='title',
                                        queryset=Tag.objects.all())

    def validate(self, data):
        """ Perform object-level validation on all the data. Called automatically
                as part of is_valid(). As per documentation, must return data
                or raise serializers.ValidationError
        """
        valid_majors = Major.objects.all()

        majors = set(data['majors'])

        # The following line is the most `pythonic` way to see if we have any
        # majors that are not real majors.
        if any(major not in valid_majors for major in majors):
            log.error('Major not found - {}'.format(major.title))
            raise serializers.ValidationError('Major(s) not found.')
        return data

    def get_validation_exclusions(self, *args, **kwargs):
        """ Add 'author' to validation exclusions, because we'll be setting it
                automatically.
        """
        exclusions = super(ProjectSerializer, self).get_validation_exclusions()
        return exclusions + ['author']
示例#14
0
class PostSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    comments = serializers.PrimaryKeyRelatedField(many=True,
                                                  read_only=True,
                                                  allow_null=True)
    post_images = DataImageSerializer(many=True,
                                      read_only=True,
                                      required=False)

    class Meta:
        model = Post
        fields = ('id', 'author', 'content', 'created_at', 'updated_at',
                  'comments', 'post_images', 'draft')
        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(PostSerializer, self).get_validation_exclusions()
        return exclusions + ['author']
示例#15
0
class PostSerializer(serializers.ModelSerializer):
    """
    read_only=True because we should not be updating an Account object with a
    PostSerializer. We also set required=False here because we will set the
    author of this post automatically.
    """
    author = AccountSerializer(read_only=True, required=False)

    class Meta:
        model = Post

        fields = ('id', 'author', 'content', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(PostSerializer, self).get_validation_exclusions()

        return exclusions + ['author']
示例#16
0
class PlayerSerializer(serializers.ModelSerializer):
    account = AccountSerializer(required=True)

    class Meta:
        model = Player

        fields = ('id', 'account', 'gold', 'level', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at', 'account')

    def update(self, instance, validated_data):
        instance.level = validated_data.get('level', instance.level)
        instance.gold = validated_data.get('gold', instance.gold)
        instance.save()
        return instance

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(PlayerSerializer, self).get_validation_exclusions()

        return exclusions + ['account']
class DeliverySerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    locked = serializers.SerializerMethodField()

    class Meta:
        model = Delivery

        fields = ('id', 'author', 'stream_name', 'activity_name',
                'view_name', 'jira_url', 'codereview_url','description','notes', 
                'status','created_at', 'updated_at', 'locked')
        read_only_fields = ('id', 'created_at', 'updated_at')
        
    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(AccountSerializer, self).get_validation_exclusions()

        return exclusions + ['author']

    def get_locked(self, obj):
        return obj.stream_name in locked
示例#18
0
class ReviewSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    story = PostSerializer(read_only=True, required=False)

    class Meta:
        model = Review

        fields = ('id', 'author', 'story', 'content_edit', 'language_well',
                  'language_improve', 'character_well', 'character_improve',
                  'setting_well', 'setting_improve', 'structure_well',
                  'structure_improve', 'theme_well', 'theme_improve',
                  'overall_comment', 'overall_rating', 'post_id', 'created_at',
                  'updated_at')

        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(ReviewSerializer, self).get_validation_exclusions()

        return exclusions + ['story', 'author']
示例#19
0
 def post(self, request, format=None):
     data = json.loads(request.body)
     email = data.get('email', None)
     password = data.get('password', None)
     account = authenticate(email=email, password=password)
     if account is not None:
         if account.is_active:
             login(request, account)
             serialized = AccountSerializer(account)
             return Response(serialized.data)
         else:
             return Response({
                 'status': 'Unauthorized',
                 'message': 'This account has been disabled.'
             }, status=status.HTTP_401_UNAUTHORIZED)
     else:
         return HttpResponse({
             'status': 'Unauthorized',
             'message': 'Username/password combination invalid.'
         }, status=status.HTTP_401_UNAUTHORIZED)
class AccountSerializerTestCase(TestCase):
    def setUp(self):
        john = Account.objects.create(email='*****@*****.**', date_of_birth=date(1989, 3, 12), password='******', username='******')
        baby = Account.objects.create(email='*****@*****.**', date_of_birth=date.today(), password='******', username='******')
        
        self.john = AccountSerializer(john)
        self.baby = AccountSerializer(baby)
    
    def test_validate_date_of_birth_success(self):
        """
        Tests if AccountSerializer.validate_date_of_birth method return 
        user.data['date_of_birth'] if the user is of legal age.
        """
        self.assertEqual(self.john.validate_date_of_birth(self.john.data['date_of_birth']), '1989-03-12')
    
    def test_validate_date_of_birth_error(self):
        """
        Tests if AccountSerializer.validate_date_of_birth method raise a 
        ValidationError if the user is too young.
        """
        self.assertRaises(ValidationError, self.baby.validate_date_of_birth, self.baby.data['date_of_birth'])
示例#21
0
    def post(self, request, format=None):
        data = request.data

        email = data.get('email', None)
        password = data.get('password', None)
        print(email)
        print(password)

        account = authenticate(email=email, password=password)

        if account is not None:
            serialized = AccountSerializer(account)
            response = Response(serialized.data)
            setCookie(account, response)
            return response
        else:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'Username/password combination invalid.'
                },
                status=status.HTTP_401_UNAUTHORIZED)
示例#22
0
class PostSerializer(serializers.ModelSerializer):
    author = AccountSerializer(read_only=True, required=False)
    shared_with = GroupSerializer(read_only=True, many=True, required=False)
    type = serializers.SerializerMethodField()

    def get_type(self, obj):
        return 'post'

    class Meta:
        model = Post

        fields = ('id', 'type', 'author', 'shared_with', 'content', 'created_at', 'updated_at', 'start_time', 'notification',
                  'notify_when', 'repeat',
                  'location_event', 'description_event', 'begin_time', 'end_time', 'end_repeat', 'show_date',
                  'show_begin_time', 'show_end_time', 'not_all_day', 'day_of_week', 'need_repeat', 'is_week_set',
                  'week_num', 'duration', 'pud', 'pud_time', 'is_holiday', 'is_updated')
        read_only_fields = ('id', 'created_at', 'updated_at')

    def get_validation_exclusions(self, *args, **kwargs):
        exclusions = super(PostSerializer, self).get_validation_exclusions()

        return exclusions + ['author']
示例#23
0
    def post(self, request, format=None):
        email = request.data.get('email', None)
        password = request.data.get('password', None)
        account = authenticate(email=email, password=password)

        if account is not None:
            if account.enabled:
                login(request, account)
                serialized = AccountSerializer(account)
                return Response(serialized.data)
            else:
                return Response(
                    {
                        'status': 'Unauthorized',
                        'detail': 'This account has been disabled.'
                    },
                    status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response(
                {
                    'status': 'Unauthorized',
                    'detail': 'Username/password combination invalid.'
                },
                status=status.HTTP_401_UNAUTHORIZED)
示例#24
0
class TransactionSerializer(serializers.ModelSerializer):
    account = AccountSerializer(read_only=False, required=False)

    class Meta:
        model = Transaction
        fields = ('id', 'account', 'montant', 'token', 'created')
示例#25
0
class VoteSerializer(serializers.ModelSerializer):
    user = AccountSerializer(read_only=True, required=False)
    poll = PollSerializer(read_only=True, required=False)
示例#26
0
 def get(self, request):
     serializer = AccountSerializer(request.user)
     return Response(serializer.data)
示例#27
0
文件: views.py 项目: Fks1998/curve
    def post(self, request, format=None):
        first_name = request.data.get('first_name', None)
        last_name = request.data.get('last_name', None)
        email = request.data.get('email', None)
        password = request.data.get('password', None)
        confirm_password = request.data.get('confirm_password', None)
        selected_dietary = request.data.get('selected_dietary', None)
        user_type = request.data.get('user_type', None)

        if first_name is None:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'FirstName is required!'
                },
                status=status.HTTP_401_UNAUTHORIZED)

        if last_name is None:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'LastName is required!'
                },
                status=status.HTTP_401_UNAUTHORIZED)

        if email is None:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'Email is required!'
                },
                status=status.HTTP_401_UNAUTHORIZED)

        if password is None:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'Password is required!'
                },
                status=status.HTTP_401_UNAUTHORIZED)

        if confirm_password is None:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'Confirm Password is required!'
                },
                status=status.HTTP_401_UNAUTHORIZED)

        if confirm_password != password:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'Password and Confirm Password is not matched!'
                },
                status=status.HTTP_401_UNAUTHORIZED)

        if user_type == 'student':
            course_name = request.data.get('course_name', None)
            selected_year = request.data.get('selected_year', None)

            if course_name is None:
                return Response(
                    {
                        'status': 'Unauthorized',
                        'message': 'Course Name is Required!'
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            if selected_year is None:
                return Response(
                    {
                        'status': 'Unauthorized',
                        'message': 'Year is Required!'
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

        if selected_dietary is None:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'Selected Dietary is Required!'
                },
                status=status.HTTP_401_UNAUTHORIZED)

        user_exist = Account.objects.filter(email=email)
        dietary_requirements = ",".join(
            [dietary['value'] for dietary in selected_dietary])

        if user_exist:
            return Response(
                {
                    'status': 'Unauthorized',
                    'message': 'User Already Exist With this Email!.'
                },
                status=status.HTTP_401_UNAUTHORIZED)
        else:
            user = Account.objects.create(email=email,
                                          username=email,
                                          first_name=first_name,
                                          last_name=last_name)
            user.set_password(password)
            user.save()
            if user_type == 'student':
                user_details = UserDetails.objects.create(
                    user=user,
                    course_name=course_name,
                    year=selected_year,
                    dietary_requirements=dietary_requirements,
                    user_type=user_type)
            else:
                j = UserDetails.objects.create(
                    user=user,
                    dietary_requirements=dietary_requirements,
                    user_type=user_type)
            user_points = UserPoints.objects.create(user=user, points=50)
            serialized = AccountSerializer(user)
            return Response(serialized.data)
        return Response(
            {
                'status': 'Unauthorized',
                'message': 'Please Try Agin Later!'
            },
            status=status.HTTP_401_UNAUTHORIZED)
 def setUp(self):
     john = Account.objects.create(email='*****@*****.**', date_of_birth=date(1989, 3, 12), password='******', username='******')
     baby = Account.objects.create(email='*****@*****.**', date_of_birth=date.today(), password='******', username='******')
     
     self.john = AccountSerializer(john)
     self.baby = AccountSerializer(baby)
示例#29
0
class OrderSerializers(BaseProductSerializer):
    """
    Serializer used to serialize whole orders
    serialize fields: 'id', 'state', 'owner', 'shippingAddress', 'postalCode', 'city', 'totalprice', 'additional_information',
        'created_at', 'last_change', 'productOrder'
    """
    owner = AccountSerializer(required=False, read_only=False)
    productOrder = ProductOrderSerializers(many=True)

    class Meta:
        """
        Definition of OrderSerializers
        """
        model = Order

        fields = (
            'id',
            'state',
            'owner',
            'shippingAddress',
            'postalCode',
            'city',
            'totalprice',
            'additional_information',
            'created_at',
            'last_change',
            'productOrder',
        )
        read_only_fields = (
            'id',
            'created_at',
            'last_change',
            'owner',
        )

    ## Method which creates productOeders object related to order
    # @return updated serialized object
    # @rtype: Order
    def create(self, validated_data):
        productOrder_data = validated_data.pop('productOrder')

        for productOrders in productOrder_data:
            prod = productOrders['product']
            prod_from_db = Product.objects.get(id=prod.id)
            if prod_from_db.available < productOrders['quantity']:
                raise Exception('Sufficient quantity of '.append(
                    prod_from_db.name).apend(' is available.'))

        order = Order.objects.create(**validated_data)

        for productOrders in productOrder_data:
            prod = productOrders['product']
            prod_from_db = Product.objects.get(id=prod.id)
            ins = ProductOrder.objects.create(order=order, **productOrders)
            Product.objects.filter(pk=prod_from_db.pk).update(
                available=prod_from_db.available - ins.quantity)
        return order

    ## Method which allows to update order parameters
    # @return updated serialized object
    # @rtype: Object
    def update(self, instance, validated_data):
        instance.state = validated_data['state']
        instance.shippingAddress = validated_data['shippingAddress']
        instance.postalCode = validated_data['postalCode']
        instance.city = validated_data['city']
        instance.totalprice = validated_data['totalprice']
        instance.additional_information = validated_data[
            'additional_information']
        instance.save()

        if id in validated_data:

            productOrder_data = validated_data.pop('productOrder')
            page_ids = [item['id'] for item in productOrder_data]
            for page in instance.productOrder:
                if page.product not in page_ids:
                    page.delete()

            # Create or update page instances that are in the request
            for item in productOrder_data:
                page = ProductOrder(id=item['id'],
                                    product=item['product'].id,
                                    price=item['price'],
                                    quantity=item['quantity'],
                                    order=instance)
                page.save()

        return instance
示例#30
0
    def get(self, request, format=None):
        first_name = request.query_params['first_name']
        last_name = request.query_params['last_name']
        email = request.query_params['email']
        queryset = []

        if last_name:
            if first_name:
                if email:
                    queryset = Account.objects.filter(
                        last_name__iexact=last_name,
                        first_name__iexact=first_name,
                        email__iexact=email)
                else:
                    queryset = Account.objects.filter(
                        last_name__iexact=last_name,
                        first_name__iexact=first_name)
            else:
                if email:
                    queryset = Account.objects.filter(
                        last_name__iexact=last_name, email__iexact=email)
                else:
                    queryset = Account.objects.filter(
                        last_name__iexact=last_name)
        else:
            if email:
                if first_name:
                    queryset = Account.objects.filter(
                        email__iexact=email, first_name__iexact=first_name)
                else:
                    queryset = Account.objects.filter(email__iexact=email)
            elif first_name:
                queryset = Account.objects.filter(
                    first_name__iexact=first_name)
            else:
                queryset = Account.objects.all()

        if not queryset:
            if last_name:
                if first_name:
                    if email:
                        queryset = Account.objects.filter(
                            last_name__icontains=last_name,
                            first_name__icontains=first_name,
                            email__iexact=email)
                    else:
                        queryset = Account.objects.filter(
                            last_name__icontains=last_name,
                            first_name__icontains=first_name)
                else:
                    if email:
                        queryset = Account.objects.filter(
                            last_name__icontains=last_name,
                            email__icontains=email)
                    else:
                        queryset = Account.objects.filter(
                            last_name__icontains=last_name)
            else:
                if email:
                    if first_name:
                        queryset = Account.objects.filter(
                            email__icontains=email,
                            first_name__icontains=first_name)
                    else:
                        queryset = Account.objects.filter(
                            email__icontains=email)
                elif first_name:
                    queryset = Account.objects.filter(
                        first_name__icontains=first_name)
                else:
                    queryset = Account.objects.all()

        serialized = AccountSerializer(queryset, many=True)
        return Response(serialized.data)
class UserProfileSerializer(serializers.ModelSerializer):
    user = AccountSerializer(read_only=True)

    class Meta:
        model = UserProfile
        fields = ('user', 'avatar', 'description', 'phone_number', 'position')
示例#32
0
class ContestantSerializerForMatch(serializers.ModelSerializer):
    account = AccountSerializer(read_only=True)

    class Meta:
        model = Contestant