Exemple #1
0
 def put(self, request, pk, format=None):
     language = self.get_object(pk=pk)
     serializer = LanguageSerializer(language, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
class MovieSerializer(serializers.ModelSerializer):

    genres = GenreSerializer(many=True)
    languages = LanguageSerializer(many=True)

    class Meta:
        model = Movie
        fields = '__all__'
    def test_update_valid_single_language_valid_payload(self):
        response = self.client.put(self.valid_update_url,
                                   data=self.valid_payload)
        test_language = Language.objects.get(pk=self.test_language.pk)
        serializer = LanguageSerializer(test_language)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, serializer.data)
Exemple #4
0
class MigrateTicketSerializer(serializers.ModelSerializer):
    group = serializers.PrimaryKeyRelatedField(
        queryset=OpportunityGroup.objects.all())
    keywords = KeywordSerializer(many=True, required=False)
    languages = LanguageSerializer(many=True, required=False)
    users_tagged = UserTaggedSerializer(required=False, many=True)
    status = serializers.CharField()
    history = HistorySerializer(many=True)
    applicants = ApplicantSerializer(many=True)
    created = serializers.DateTimeField(required=False)
    files = UploadedFileSerializer(required=False, many=True)
    ratings = RatingSerializer(required=False, many=True)

    class Meta:
        model = Opportunity
        fields = [
            'group',
            'title',
            'description',
            'keywords',
            'deadline_date',
            'slug',
            'mode',
            'uuid',
            'target',
            'users_tagged',
            'created',
            'status',
            'history',
            'applicants',
            'files',
            'ratings',
            'languages',
        ]

    def create(self, validated_data):
        keywords = Keyword.objects.update_keywords(
            user_from=validated_data.get('user_from'),
            keywords_name=[k['name'] for k in validated_data.get('keywords')],
        )
        validated_data['keywords'] = keywords
        languages = Language.objects.update_languages(
            user_from=validated_data.get('user_from'),
            languages_name=set(
                [k['name'] for k in validated_data.get('languages', [])]),
        )
        validated_data['languages'] = languages
        validated_data['users_tagged'] = [
            u['user'] for u in validated_data.get('users_tagged', [])
        ]
        return create_opportunity_from_ticket(**validated_data)

    def to_representation(self, obj):
        return {'uuid': obj.uuid.__str__()}
    def test_get_all_paradigms(self):
        """
        Test case for getting list of existing languages.
        """
        response = self.client.get(self.list_url)

        languages = Language.objects.all()
        serializer = LanguageSerializer(languages, many=True)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, serializer.data)
    def test_get_valid_single_language(self):
        """
        Test case for getting the single paradigm.
        """
        # Get a language instance with GET.
        response = self.client.get(self.valid_detail_url)
        # Get a language instance from test db.
        test_language = Language.objects.get(pk=response.data['id'])
        serializer = LanguageSerializer(test_language)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, serializer.data)
    def test_post_valid_single_language(self):
        """
        Test case for creating a valid language instance.
        """
        # Create a language instance with POST.
        response = self.client.post(self.create_url,
                                    data={
                                        'name': 'test_language',
                                        'paradigm': [self.test_paradigm.pk]
                                    })
        # Get created language instance from test db.
        test_language = Language.objects.get(pk=response.data['id'])
        serializer = LanguageSerializer(test_language)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data, serializer.data)
Exemple #8
0
class OpportunityDetailSerializer(OpportunityUserMixin, serializers.ModelSerializer):
    keywords = KeywordSerializer(many=True, required=False)
    languages = LanguageSerializer(many=True, required=False)
    userStatus = serializers.SerializerMethodField()
    userActions = serializers.SerializerMethodField()
    applicants = serializers.SerializerMethodField()
    myApplicant = serializers.SerializerMethodField()
    requestedBy = serializers.SerializerMethodField()
    newApplicants = serializers.SerializerMethodField()
    questions = serializers.SerializerMethodField()
    budgets = BudgetSerializer(many=True)
    status = serializers.CharField()
    users_tagged = serializers.SerializerMethodField()
    exo_role = ExORoleSerializer()
    certification_required = CertificationRoleSerializer()
    files = serializers.SerializerMethodField()
    info_detail = serializers.SerializerMethodField()

    class Meta:
        model = Opportunity
        fields = [
            'pk', 'slug', 'uuid',
            'title', 'description', 'keywords', 'questions',
            'languages',
            'mode', 'location', 'place_id', 'location_url',
            'start_date', 'modified', 'created',
            'duration_unity', 'duration_value',
            'exo_role', 'certification_required', 'entity',
            'other_role_name', 'other_category_name',
            'userStatus', 'userActions',
            'budgets',
            'applicants', 'myApplicant', 'requestedBy',
            'newApplicants', 'files',
            'num_positions', 'deadline_date',
            'status', 'users_tagged', 'target',
            'has_been_edited', 'info_detail',
        ]
        read_only_fields = ['slug', 'modified', 'uuid']

    @property
    def is_admin_action(self):
        action = ''
        try:
            action_by_default = self.context.get('view').action
            action = self.context.get('action', action_by_default)
        except Exception:
            pass
        return action in [
            'admin', 'assign', 'close', 'reject', 're_open']

    def get_applicants(self, obj):
        if self.is_admin_action:
            queryset = obj.applicants_info.all().order_by_status()
            return OpportunityApplicantSerializer(
                queryset, many=True,
                context=self.context).data
        return []

    def get_myApplicant(self, obj):
        context = self.context.get('request')
        my_applicant = obj.get_applicants_for_user(context.user).first()
        if not my_applicant:
            return None
        return OpportunityApplicantSerializer(
            instance=my_applicant,
            context=self.context).data

    def get_userActions(self, obj):
        return obj.user_actions(
            self.context.get('request').user,
            remove_admin_actions=not self.is_admin_action,
        )

    def get_newApplicants(self, obj):
        user = self.context.get('request').user
        ct = ContentType.objects.get_for_model(user)
        last_see_action = obj.action_object_actions.filter(
            actor_content_type=ct,
            actor_object_id=str(user.id),
            verb=settings.OPPORTUNITIES_ACT_ACTION_SEE).first()
        if not last_see_action:
            return obj.applicants.count()
        else:
            timestamp = last_see_action.timestamp
            return obj.applicants_info.filter(created__gte=timestamp).count()

    def get_questions(self, obj):
        questions = obj.questions.all().order_by('id')
        return QuestionSerializer(questions, many=True).data

    def get_requestedBy(self, obj):
        if obj.is_draft:
            user = obj.user_created_by
        else:
            user = obj.requested_by
        return OpportunityStatusSerializer(user).data

    def get_users_tagged(self, obj):
        response = []
        for user_tagged in obj.users_tagged.all():
            user = user_tagged.user
            user_wrapper = UserWrapper(user=user)
            response.append(UserSerializer(user_wrapper).data)
        return response

    def get_files(self, obj):
        return UploadedFileRelatedGenericSerializer(
            obj.files.all(), many=True, context=self.context).data

    def get_info_detail(self, obj):
        if obj.group:
            return obj.group.info_detail
        return obj.context_info_detail
Exemple #9
0
class OpportunitySerializer(OpportunityMixin, OpportunityUserMixin,
                            serializers.ModelSerializer):

    userBy = serializers.SerializerMethodField()
    keywords = KeywordSerializer(many=True, required=False)
    languages = LanguageSerializer(many=True, required=False)
    userStatus = serializers.SerializerMethodField()
    userActions = serializers.SerializerMethodField()
    numApplicants = serializers.SerializerMethodField()
    alreadyVisited = serializers.SerializerMethodField()
    isNew = serializers.SerializerMethodField()
    questions = QuestionSerializer(many=True, required=False)
    comment = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    send_notification = serializers.BooleanField(required=False)
    budgets = BudgetSerializer(required=False, many=True)
    users_tagged = UserTaggedSerializer(required=False, many=True)
    duration_unity = serializers.ChoiceField(
        required=False, choices=settings.OPPORTUNITIES_DURATION_UNITY_CHOICES)
    duration_value = serializers.IntegerField(required=False)
    exo_role = serializers.SlugRelatedField(queryset=ExORole.objects.all(),
                                            slug_field='code',
                                            required=True)
    certification_required = serializers.SlugRelatedField(
        queryset=CertificationRole.objects.all(),
        slug_field='code',
        required=False,
        allow_null=True)
    files = UploadedFileSerializer(many=True, required=False)
    group = serializers.PrimaryKeyRelatedField(
        queryset=OpportunityGroup.objects.all(), required=False)

    class Meta:
        model = Opportunity
        fields = [
            'pk',
            'slug',
            'uuid',
            'comment',
            'send_notification',
            'title',
            'description',
            'keywords',
            'languages',
            'mode',
            'location',
            'place_id',
            'location_url',
            'start_date',
            'modified',
            'entity',
            'exo_role',
            'certification_required',
            'other_role_name',
            'userStatus',
            'userBy',
            'other_category_name',
            'budgets',
            'alreadyVisited',
            'isNew',
            'userActions',
            'numApplicants',
            'questions',
            'num_positions',
            'deadline_date',
            'users_tagged',
            'target',
            'duration_unity',
            'duration_value',
            'files',
            'group',
            'context_object_uuid',
            'context_content_type',
        ]
        read_only_fields = ['slug', 'modified', 'uuid']
        extra_kwargs = {
            'description': {
                'allow_blank': False,
                'required': True,
                'allow_null': False,
            },
        }

    def validate(self, data):
        action = self.context.get('view').action
        group = data.get('group')
        user = self.context.get('request').user

        if action == 'update':
            opportunity = self.context.get('view').get_object()
            can_update_opportunity = opportunity.can_do_actions(
                user, settings.OPPORTUNITIES_ACTION_CH_EDIT)
            if not can_update_opportunity:
                raise serializers.ValidationError(
                    "You can't update this opportunity")
        if group:
            if action in ['create', 'preview']:
                previous_opp = None
            else:
                previous_opp = self.instance
            position_availables = group.has_positions_availables(
                data.get('num_positions'),
                previous_opp,
            )
            if not position_availables:
                raise serializers.ValidationError("No positions availables")

        if 'other_category_name' not in data and \
                data['exo_role'].categories.first().code == settings.EXO_ROLE_CATEGORY_OTHER:
            raise serializers.ValidationError(
                detail='Other Category name is required')

        if 'other_category_name' in data and data['other_category_name'] and \
                data['exo_role'].categories.first().code != settings.EXO_ROLE_CATEGORY_OTHER:
            raise serializers.ValidationError(detail='Invalid Category')

        return data

    def create(self, validated_data):
        keywords = Keyword.objects.update_keywords(
            user_from=validated_data.get('user_from'),
            keywords_name=[k['name'] for k in validated_data.get('keywords')],
        )
        validated_data['keywords'] = keywords
        languages = Language.objects.update_languages(
            user_from=validated_data.get('user_from'),
            languages_name=set(
                [k['name'] for k in validated_data.get('languages', [])]),
        )
        validated_data['languages'] = languages
        validated_data['users_tagged'] = [
            u['user'] for u in validated_data.get('users_tagged', [])
        ]
        group = validated_data.pop('group', None)
        if group:
            return Opportunity.objects.create_opportunity_in_group(
                user_from=validated_data.pop('user_from'),
                group=group,
                **validated_data)
        else:
            return Opportunity.objects.create_opportunity(
                user_from=validated_data.pop('user_from'), **validated_data)

    def add_id_to_questions(self, validated_data):
        validated_data['questions'] = self.initial_data.get('questions')

    def update(self, instance, validated_data):
        keywords = Keyword.objects.update_keywords(
            user_from=validated_data.get('user_from'),
            keywords_name=[k['name'] for k in validated_data.get('keywords')],
        )
        validated_data['keywords'] = keywords
        languages = Language.objects.update_languages(
            user_from=validated_data.get('user_from'),
            languages_name=set(
                [k['name'] for k in validated_data.get('languages', [])]),
        )
        validated_data['languages'] = languages
        self.add_id_to_questions(validated_data)
        validated_data['users_tagged'] = [
            u['user'].uuid for u in validated_data.get('users_tagged', [])
        ]
        opportunity = Opportunity.objects.update_opportunity(
            user_from=validated_data.pop('user_from'),
            opportunity=instance,
            **validated_data)
        instance.refresh_from_db()
        return opportunity
Exemple #10
0
 def get(self, request, pk, format=None):
     language = self.get_object(pk=pk)
     serializer = LanguageSerializer(language)
     return Response(serializer.data)
Exemple #11
0
 def post(self, request, format=None):
     serializer = LanguageSerializer(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)
Exemple #12
0
 def get(self, request, format=None):
     languages = Language.objects.all()
     serializer = LanguageSerializer(languages, many=True)
     return Response(serializer.data)