Esempio n. 1
0
    def create(self, request, *args, **kwargs):
        user_id = request.user.id
        property_id = request.data['property_id']
        message = request.data['message'] if 'message' in request.data else None

        # Check if the chat is not created
        existing_chat = Chat.objects.filter(
            (Q(from_user_id=user_id) & Q(property_id=property_id)))
        if existing_chat.count() > 0:
            raise NotAcceptable('Chat already exists. Please, go to Chats')

        _property = Property.objects.get(id=property_id)
        if not _property:
            raise NotAcceptable('Property does not exist')

        chat = Chat(property=_property,
                    from_user_id=user_id,
                    to_user_id=_property.owner_id)
        chat.save()

        if message:
            create_message(chat.id, user_id, request.data['message'])

        serializer = ChatSerializer(chat)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
Esempio n. 2
0
    def perform_crs_negotation(self, request):
        # don't cripple the browsable API...
        if isinstance(request.accepted_renderer, BrowsableAPIRenderer):
            return

        # methods with request bodies need to have the CRS specified
        if request.method.lower() in ("post", "put", "patch"):
            content_crs = extract_header(request, HEADER_CONTENT)
            if content_crs is None:
                raise PreconditionFailed(
                    detail=f"'{HEADER_CONTENT}' header ontbreekt")
            if content_crs != DEFAULT_CRS:
                raise NotAcceptable(
                    detail=f"CRS '{content_crs}' is niet ondersteund")

        if request.method.lower() == "delete":
            return

        # client must indicate which CRS they want in the response
        requested_crs = extract_header(request, HEADER_ACCEPT)
        if requested_crs is None:
            raise PreconditionFailed(
                detail=f"'{HEADER_ACCEPT}' header ontbreekt")

        if requested_crs != DEFAULT_CRS:
            raise NotAcceptable(
                detail=f"CRS '{requested_crs}' is niet ondersteund")
Esempio n. 3
0
 def create(self, request, *args, **kwargs):
     data = self.request.data.get(
         "items") if 'items' in self.request.data else self.request.data
     userDetail = UserDetails.objects.filter(user=request.user).first()
     shop = request.data.get('shop')
     if not userDetail.is_customer:
         shopDetail = Shop.objects.filter(
             id=self.request.data.get('shop')).first()
         if shopDetail is not None and shopDetail.user == userDetail.user:
             many = isinstance(data, list)
             if many:
                 for x in data:
                     x['shop'] = shop
             serializer = self.get_serializer(data=data, many=many)
             serializer.is_valid(raise_exception=True)
             self.perform_create(serializer)
             headers = self.get_success_headers(serializer.data)
             return Response(serializer.data,
                             status=status.HTTP_201_CREATED,
                             headers=headers)
         else:
             raise NotAcceptable(
                 "You are not allowed to create items for other users.")
     else:
         raise NotAcceptable("Customers are not allowed to create shops.")
Esempio n. 4
0
def idea_register(request, idea_id):
    """
    Endpoint to register user into an idea
    ---
    POST:
        serializer: ideas.serializers.IdeaRegistrationSerializer
    """
    serializer = IdeaRegistrationSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        idea = get_object_or_404(Idea, pk=idea_id)
        user = get_object_or_404(User, pk=serializer.validated_data['user_id'])

        previous_records = IdeaParticipant.objects.filter(user=user)
        if len(previous_records) > 0:
            for record in previous_records:
                if record.idea.event == idea.event:
                    raise NotAcceptable(config.PARTICIPANT_IDEA_RESTRICTION)

        number_participants = IdeaParticipant.objects.filter(idea=idea).count()
        if config.TEAM_MAX_SIZE > number_participants and idea.is_completed is False:
            try:
                IdeaParticipant.objects.create(idea=idea, user=user)
                if IdeaParticipant.objects.filter(idea=idea).count() == config.TEAM_MAX_SIZE:
                    idea.is_completed = True
                    idea.save()
            except Exception as e:
                print(e)
                raise NotAcceptable(config.PARTICIPANT_REGISTERED)
        else:
            raise ValidationError(
                {'detail': config.TEAM_MAX_SIZE_MESSAGE})
        participants = IdeaParticipant.objects.filter(idea=idea)
        serializer = IdeaParticipantsSerializer(participants, many=True)
        return Response({"is_registered": True,
                         "team_members": serializer.data}, status=status.HTTP_201_CREATED)
    def post(self, request, pk, user_id, action):
        community = get_object_or_404(Community, pk=pk, valid=True)
        self.check_object_permissions(request, community)

        if community.members.filter(id=user_id, membership__valid=True):
            raise NotAcceptable('此成员已经通过审核。')
        elif not community.members.filter(id=user_id):
            raise NotAcceptable('此成员不在审核列表上。')

        member = community.membership_set.get(user_id=user_id)
        related_user = community.members.get(id=user_id)
        subtype_ca = 1
        subtype_c_ap = 2
        with transaction.atomic():
            if action == 'allow':
                description = '加入社团请求被通过。'
                NoticeManager.create_notice_CA(related_user, community,
                                               subtype_ca, description)
                NoticeManager.create_notice_C_AP(related_user, community,
                                                 subtype_c_ap)

                member.valid = True
                member.save()
            elif action == 'deny':
                description = '加入社团请求被拒绝。'
                NoticeManager.create_notice_CA(related_user, community,
                                               subtype_ca, description)

                member.delete()
            else:
                raise NotAcceptable('错误的操作。')

        return Response(status=status.HTTP_200_OK)
    def post(self, request, pk):
        community = get_object_or_404(Community, pk=pk, valid=True)
        serializer = CommunityJoinSerializer(data=request.data)
        user_status = community.get_member_status(request.user)
        if serializer.is_valid():
            # fixme: put following validation logic into serializer
            # maybe serializers.SerializerMethodField() is useful here?
            with transaction.atomic():
                admin = community.admins.filter(id=request.user.pk)
                if not admin:
                    if serializer.validated_data['join']:
                        if user_status['member']:
                            raise NotAcceptable(
                                f'你目前已经为社团成员 ({"正式" if user_status["valid"] else "待审核"})'
                            )
                        NoticeManager.create_notice_C_AA(
                            request.user, community)
                        community.members.add(request.user)
                    else:
                        if user_status['member']:
                            if request.user != community.owner:
                                community.members.remove(request.user)
                            else:
                                raise NotAcceptable('社团所有者无法直接退出社团。')
                        else:
                            raise NotAcceptable('你不是此社团成员!')
                    return Response(community.get_member_status(request.user))
                else:
                    raise NotAcceptable('社团的管理员用户无法直接修改自己的加入状态。')

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 7
0
    def get(self, request):
        params = request.GET
        if not request.user.is_authenticated:
            raise NotAuthenticated(detail='Not Authenticated')

        if not params:
            response = totals_utils.get_all_friends_total(request.user)

        elif params.get('filter') == 'current_user':
            response = totals_utils.get_current_user_total(request.user)

        elif params.get('friend_id'):
            friend_id = params.get('friend_id')
            try:
                friend = User.objects.get(pk=uuid.UUID(friend_id))
            except:
                raise NotFound(detail='Friend ID given is incorrect')

            if request.user == friend:
                raise NotAcceptable(
                    detail='Friend ID given is equal to Current User ID')

            response = totals_utils.get_friend_total(request.user, friend)

        else:
            raise NotAcceptable(detail='Invalid query')

        return Response(response)
Esempio n. 8
0
    def get(self, _, templates):
        templates = templates.split(",")
        response = {}

        for template in templates:
            try:
                view_name, view_method = template.split(".")
            except ValueError:
                if not template in self.allowed_templates:
                    raise NotAcceptable("Template: {}".format(template))

                loader = Loader()
                name = "{}.html".format(template)
                template_body = loader.load_template_source(name)[0]

                response[template] = self.reformat_template(template_body)
            else:
                if view_name not in self.allowed_views.keys():
                    raise NotAcceptable("View: {}".format(view_name))

                view = self.allowed_views[view_name]

                if view_name in self.allowed_methods.keys() and \
                  view_method not in self.allowed_methods[view_name]:
                    raise NotAcceptable("Method: {}.{}".format(
                        view_name, view_method))

                views = getattr(view, view_method)()

                response[view_name] = views
                # response.update({"{}.{}".format(view_name, name): template_body\
                # 	for name, template_body in views.items()})

        return Response(response)
Esempio n. 9
0
    def validate(self, attrs):
        amount_to_be_transferred = attrs.get('amount_to_be_transferred', '')
        destination_account_number = attrs.get('destination_account_number', '')
        user_name = attrs.get('user_name', '')

        # TODO check if my limit is ok, not implemented yet

        current_balance = self.context['current_balance']
        current_username = self.context['current_username']
        balance_after_transaction = self.context['balance_after_transaction']
        current_id = self.context['current_id']
        current_account_number = self.context['current_account_number']

        if user_name != current_username:
            raise NotAcceptable(f"Please check your user name")

        if current_account_number == destination_account_number:
            raise NotAcceptable(f"Please check destination account number: {destination_account_number}")

        if amount_to_be_transferred > current_balance:
            raise NotAcceptable(
                f"You don't have enough money, your current balance is R$ {current_balance}")

        qs = UserBankAccount.objects.filter(account_no=destination_account_number)
        if not qs.exists():
            raise NotAcceptable(f"Wrong destination account number: {destination_account_number}")

        return {
            'amount_to_be_transferred': amount_to_be_transferred,
            'destination_account_number': destination_account_number,
            'user_name': user_name,
            'balance_after_transaction': balance_after_transaction,
            'current_id': current_id,
            'transaction_type': TRANSFER_MONEY
        }
Esempio n. 10
0
    def validate(self, attrs):
        amount = attrs.get('amount', '')

        min_withdrawal_amount = settings.MINIMUM_WITHDRAWAL_AMOUNT
        # Grabbing the custom context data
        maximum_withdrawal = self.context['maximum_withdrawal']
        balance_after_transaction = self.context['balance_after_transaction']
        user_account_id = self.context['user_account_id']
        current_balance = self.context['current_balance']

        if amount < min_withdrawal_amount:
            raise NotAcceptable(f'You need to withdrawal at least R$ {min_withdrawal_amount}')

        if amount > maximum_withdrawal:
            raise NotAcceptable(f'You only can withdrawal a maximum of R$ {maximum_withdrawal}')

        if amount > current_balance:
            raise NotAcceptable(
                f"You don't have enough money, your current balance is R$ {current_balance}")

        return {
            'account': user_account_id,
            'amount': amount,
            'balance_after_transaction': balance_after_transaction,
            'transaction_type': WITHDRAWAL,
        }
Esempio n. 11
0
 def create_multiple_from_template(self, vmachine, pmachineguids, amount,
                                   start, name, description):
     """
     Creates a certain amount of vMachines based on a vTemplate
     """
     if len(pmachineguids) == 0:
         raise NotAcceptable
     try:
         for pmachienguid in pmachineguids:
             _ = PMachine(pmachienguid)
     except ObjectNotFoundException:
         raise Http404('pMachine could not be found')
     if vmachine.is_vtemplate is False:
         raise NotAcceptable('vMachine is not a vTemplate')
     if not isinstance(amount, int) or not isinstance(start, int):
         raise NotAcceptable('Fields amount and start should be numeric')
     amount = max(1, amount)
     start = max(0, start)
     return VMachineController.create_multiple_from_template.delay(
         machineguid=vmachine.guid,
         pmachineguids=pmachineguids,
         amount=amount,
         start=start,
         name=str(name),
         description=str(description))
Esempio n. 12
0
def create_ticket_envelope_pre_save(sender, instance, *args, **kwargs):
    driver_has_active_trip = Trip.objects.has_active_trip(instance.driver)
    if not driver_has_active_trip:
        raise NotAcceptable('Driver trip\'s is not active')

    # check driver is not a passenger
    if instance.driver == instance.passenger:
        raise NotAcceptable('Conversation can not between one person!')

    # check each passenger has just one ticket.
    tickets = TicketEnvelope.objects.filter(trip=instance.trip)
    if not instance.pk:
        for ticket in tickets:
            if ticket.passenger == instance.passenger:
                raise NotAcceptable('Active conversation is now available')

        # check tickets reach to 4
        if len(tickets) == 4:
            raise NotAcceptable(
                'Now, 4 tickets are available, you can\'t create more envelope.'
            )

        today = khayyam.JalaliDatetime.now().strftime('%y%m%d')
        security_code = secrets.token_hex(3)
        instance.sku = '{}{}'.format(today, security_code)

    END = 2
    if instance.trip.status == END:
        raise Exception('Trip is Ended. We can\'t send your message')
Esempio n. 13
0
    def update(self, instance, validated_data):
        updated = super().update(instance, validated_data)
        default_facility = Facility.objects.default_facility()

        user_pk = self.context.get("user_pk")
        user = User.objects.get(id=user_pk)

        # Administrator cannot change away fro a facility he/she created
        if user.is_administrator:
            raise NotAcceptable({
                "response_code":
                1,
                "response_message":
                f"You cannot change your facility from {user.facility.title} because you created it"
            })

        # Take the professional back to default facility and make use visible to facilities for recruitment
        if 'is_available' in validated_data:
            availability_status = validated_data['is_available']
            if availability_status == True:
                user.facility = default_facility
                user.save()
                updated.is_available = availability_status
                updated.facility = default_facility
                updated.save()
            else:
                raise NotAcceptable({"response_message": f"Not acceptable"})

        return updated
Esempio n. 14
0
def idea_vote(request, event_id):
    """
    Endpoint to vote for an idea
    ---
    POST:
        serializer: ideas.serializers.IdeaVoteSerializer
    """
    if request.method == "POST":
        serializer = IdeaVoteSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            idea = get_object_or_404(Idea, pk=serializer.validated_data['idea_id'])
            user = request.user
            event = get_object_or_404(Event, pk=event_id)
            own_idea = IdeaParticipant.objects.filter(idea=idea, user=user).count()
            if own_idea > 0:
                raise NotAcceptable("No puedes votar por tu propia idea.")
            try:
                IdeaVotes.objects.create(event=event, idea=idea, participant=user)
            except Exception as e:
                print(e)
                raise NotAcceptable(config.USER_VOTED)
    event_ideas = []
    ideas = get_list_or_404(Idea, event=event_id, is_valid=True, is_completed=True)
    for idea in ideas:
        votes = IdeaVotes.objects.filter(idea=idea).count()
        idea_response = {'id': idea.id,
                         'title': idea.title,
                         'votes': votes}
        event_ideas.append(idea_response)
    serializer = IdeaSerializerWithVotes(event_ideas, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)
Esempio n. 15
0
    def partial_update(self, storagerouter, request, contents=None):
        """
        Update a StorageRouter
        """
        contents = None if contents is None else contents.split(',')
        previous_primary = storagerouter.primary_failure_domain
        previous_secondary = storagerouter.secondary_failure_domain
        serializer = FullSerializer(StorageRouter,
                                    contents=contents,
                                    instance=storagerouter,
                                    data=request.DATA)
        if serializer.is_valid():
            primary = storagerouter.primary_failure_domain
            secondary = storagerouter.secondary_failure_domain
            if primary is None:
                raise NotAcceptable(
                    'A StorageRouter must have a primary FD configured')
            if secondary is not None:
                if primary.guid == secondary.guid:
                    raise NotAcceptable(
                        'A StorageRouter cannot have the same FD for both primary and secondary'
                    )
                if len(secondary.primary_storagerouters) == 0:
                    raise NotAcceptable(
                        'The secondary FD should be set as primary FD by at least one StorageRouter'
                    )
            if len(previous_primary.secondary_storagerouters) > 0 and len(previous_primary.primary_storagerouters) == 1 and \
                    previous_primary.primary_storagerouters[0].guid == storagerouter.guid and previous_primary.guid != primary.guid:
                raise NotAcceptable(
                    'Cannot change the primary FD as this StorageRouter is the only one serving it while it is used as secondary FD'
                )
            serializer.save()
            if previous_primary != primary or previous_secondary != secondary:
                cache = VolatileFactory.get_client()
                key_mds = 'ovs_dedupe_fdchange_mds_{0}'.format(
                    storagerouter.guid)
                key_dtl = 'ovs_dedupe_fdchange_dtl_{0}'.format(
                    storagerouter.guid)
                task_mds_id = cache.get(key_mds)
                task_dtl_id = cache.get(key_dtl)
                if task_mds_id:
                    # Key exists, task was already scheduled. If task is already running, the revoke message will be ignored
                    revoke(task_mds_id)
                if task_dtl_id:
                    revoke(task_dtl_id)
                async_mds_result = MDSServiceController.mds_checkup.s(
                ).apply_async(countdown=60)
                async_dtl_result = VDiskController.dtl_checkup.s().apply_async(
                    countdown=60)
                cache.set(key_mds, async_mds_result.id,
                          600)  # Store the task id
                cache.set(key_mds, async_dtl_result.id,
                          600)  # Store the task id

            return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 16
0
def check_tasks_csv(csv_file, organizer):
    oid = organizer.org.oid
    task_list = []
    input_fields = [
        'title', 'duration', 'address', 'manager_id', 'image_required',
        'collect_demand', 'other_fields'
    ]
    flag, csv_dict = check_csv_fields(csv_file, input_fields, ';')
    for row in csv_dict:
        if row is None:
            break
        try:
            title = row['title']
            duration = int(row['duration'])
            address = row['address']
            manager = clean_whs(row['manager_id'])

            if len(manager) < 1:
                err_msg = 'Manager not provided!'
                raise NotAcceptable(detail=err_msg)

            manager_qs = User.objects.filter(
                Q(username=create_username(oid, manager)))
            if not manager_qs.exists():
                err_msg = 'Manager: ' + manager + ' not found!'
                raise NotAcceptable(detail=err_msg)
            manager = manager_qs[0]

            image_req = bool(int(row['image_required']))
            demand = bool(int(row['collect_demand']))
            other_fields = str(row['other_fields']).split(',')

        except Exception as e:
            err_msg = str(e)
            raise NotAcceptable(detail=err_msg)

        task_list.append({
            'title': title,
            'duration': duration,
            'address': address,
            'manager': manager,
            'agents': [],
            'image_req': image_req,
            'demand': demand,
            'other_fields': other_fields,
        })

    # print(task_list)
    new_task = len(task_list)
    task_limit = organizer.org.subscription.task_limit
    consumed_tasks = organizer.org.subscription.current_usage.consumed_tasks
    if new_task + consumed_tasks > task_limit:
        diff = (new_task + consumed_tasks) - task_limit
        err_msg = 'Task limit exceeded! Please upgrade for another ' + str(
            diff) + ' tasks!'
        raise NotAcceptable(detail=err_msg)

    return task_list
Esempio n. 17
0
    def upload_location(self, validated_data, request):
        agent = request.user
        agent_qs = User.objects.filter(id=agent.id)
        presence = agent.is_present
        remaining_task = Task.objects.filter(
            Q(agent_list=agent) & Q(status=TSD['In progress'])).exists()
        loc_reply = None

        with transaction.atomic():
            loc = self.create(validated_data)
            loc.agent = agent
            loc.org = agent.org

            if presence:
                loc.on_task_id = agent.userstate.active_task_id
            address = get_address(loc.point['lat'], loc.point['lng'])
            loc.address = address
            loc.save()
            event_timestamp = loc.timestamp

            UserState.objects.filter(Q(user=agent)).update(last_location=loc)

            # invalid_upload = not presence and loc.event != EVENT_DICT['To Online']
            # cur_device = agent.userstate.current_device
            # invalid_device = cur_device and loc.mac != cur_device.mac

            if not presence and loc.event != EVENT_DICT['To Online']:
                msg = 'invalid_upload'
                raise NotAcceptable(detail=msg)

            if loc.event == EVENT_DICT['To Online']:
                if presence:
                    msg = 'Already present!'
                    raise NotAcceptable(detail=msg)

                exec_online_event(user=agent, entry_timestamp=event_timestamp)
                presence = True
                attendance_notification(agent, presence)

            if loc.event == EVENT_DICT['To Offline']:
                # if remaining_task:
                #     msg = 'Task is in progress!'
                #     raise NotAcceptable(detail=msg)

                exec_offline_event(user=agent, exit_timestamp=event_timestamp)
                presence = False
                attendance_notification(agent, presence)

            agent_qs.update(is_working=remaining_task,
                            is_awol=False,
                            is_present=presence,
                            ping_count=0)

            loc_reply = {
                'presence': presence,
                'location_interval': agent.org.location_interval,
            }
        return loc_reply
Esempio n. 18
0
 def clust_boxplot(self, request, pk=None):
     k = try_int(self.request.GET.get('k'), -1)
     col_index = try_int(self.request.GET.get('index'), -1)
     if k == -1:
         raise NotAcceptable("k parameter required")
     if col_index == -1:
         raise NotAcceptable("col_index parameter required")
     object = self.get_object()
     return Response(object.get_clust_boxplot_values(k, col_index))
Esempio n. 19
0
 def ks(self, request, pk=None):
     vector_id = try_int(self.request.GET.get('vector_id'), -1)
     matrix_id = try_int(self.request.GET.get('matrix_id'), -1)
     if vector_id == -1:
         raise NotAcceptable("Vector `id` parameter required")
     if matrix_id == -1:
         raise NotAcceptable("Matrix `id` parameter required")
     object = self.get_object()
     return Response(object.get_ks(vector_id, matrix_id))
Esempio n. 20
0
    def create(self, request, *args, **kwargs):
        data = self.request.data

        if "basket" not in data:
            raise NotAcceptable(detail="Target basket needs to be specified.")

        basket = Basket.objects.get(id=data.get("basket"))
        basket_variables = []
        basket_size = BasketVariable.objects.filter(basket=basket.id).count()

        self._test_exclusivity(
            ["variables" in data, "concept" in data, "topic" in data])

        variable_filter = {}

        if "variables" in data:
            variable_filter = {"id__in": data["variables"]}

        if "topic" in data:
            topic_object: Topic = Topic.objects.get(name=data["topic"],
                                                    study=basket.study)
            variable_filter = {
                "concept__topics__in": topic_object.get_topic_tree_leaves()
            }

        if "concept" in data:
            concept = Concept.objects.get(name=data["concept"])
            variable_filter = {"concept": concept}

        if "study" in data:
            variable_filter["dataset__study__name"] = data["study"]

        variables = Variable.objects.filter(
            ~Q(baskets_variables__basket=basket), **variable_filter)

        if len(variables) + basket_size > self.basket_limit:
            raise NotAcceptable(detail=self._basket_limit_error_message(
                basket_size, len(variables)))
        for variable in variables:
            basket_variables.append(
                BasketVariable(variable=variable, basket=basket))

        BasketVariable.objects.bulk_create(basket_variables)
        if len(variables) == 0:
            return Response(
                {"detail": "No new variables to add to this Basket."},
                status=status.HTTP_200_OK,
            )

        return Response(
            {
                "detail":
                "Successfully added " + str(len(variables)) +
                " variables to this Basket."
            },
            status=status.HTTP_201_CREATED,
        )
Esempio n. 21
0
    def validate_product_cost(self, data):
        try:
            product_cost = int(data)
            if float(product_cost) <= 0:
                raise NotAcceptable('cost cannot be 0 or negative')
        except NotAcceptable:
            raise NotAcceptable('cost must be a number')

        return data
Esempio n. 22
0
 def cluster_details(self, request, pk=None):
     k = try_int(self.request.GET.get('k'), -1)
     cluster_id = try_int(self.request.GET.get('cluster_id'), -1)
     if k == -1:
         raise NotAcceptable('`k` parameter required')
     if cluster_id == -1:
         raise NotAcceptable('`cluster_id` parameter required')
     object = self.get_object()
     return Response(object.get_cluster_members(k, cluster_id))
Esempio n. 23
0
 def has_permission(self, request, view):
     if request.user.is_authenticated:
         if request.user.cadre:
             if request.user.cadre.cluster == "PHARMACY":
                 return True
             else:
                 raise NotAcceptable(
                     "Pharmacists or Pharmaceutical Technologists only")
     else:
         raise NotAcceptable("Pharmacists only")
Esempio n. 24
0
 def get_queryset(self) -> QuerySet:
     n = self.request.GET.get('n', 12)
     try:
         n = int(n)
     except ValueError:
         raise NotAcceptable('Invalid value for n provided.')
     if n >= 20:
         raise NotAcceptable("Can't retrieve more than 20 articles.")
     articles = Article.objects.filter(draft=False)[:n]
     return articles
Esempio n. 25
0
 def _test_exclusivity(self, values: List[bool]) -> bool:
     """Check if only one boolean in list of booleans is True."""
     mutually_exclusive_violation = 0
     for value in values:
         mutually_exclusive_violation += value
     if mutually_exclusive_violation > 1:
         raise NotAcceptable(
             detail=
             "Keys topic, concept and variables are mutually exclusive.")
     if mutually_exclusive_violation == 0:
         raise NotAcceptable(detail=self.DATA_MISSING_ERROR_MESSAGE)
Esempio n. 26
0
    def perform_create(self, serializer):
        user = get_object_or_404(Passageiro, user=self.request.user)
        driver = util.get_available_driver()

        if user.has_active_race():
            raise NotAcceptable({"message": "Usuário já está em uma corrida."})

        if driver:
            serializer.save(passageiro=user, motorista=driver)
        else:
            raise NotAcceptable({"message": "Nenhum motorista disponível."})
    def validate_value(self, property, value):
        if value is not None:
            if not isinstance(value, int):
                raise NotAcceptable(self.error_msgs['invalid_type'].format(
                    property=property, type=type(value)))
            if value < 0:
                raise NotAcceptable(self.error_msgs['less_than_zero'].format(
                    property=property))

        if property == 'limit' and value == 0:
            raise NotAcceptable(self.error_msgs['limit_is_zero'])
Esempio n. 28
0
 def create_obj(self, validated_data):
     username = validated_data.get('username', None)
     username_qs = User.objects.filter(username=username)
     if username_qs.exists():
         raise NotAcceptable(detail='username exists!')
     validate_username(username)
     try:
         user = self.create(validated_data)
     except Exception as e:
         print(str(e))
         raise NotAcceptable(detail='Something went wrong!')
     return user
Esempio n. 29
0
 def delete(self, request, *args, **kwargs):
     if self.request.user == self.get_object():
         raise NotAcceptable(u'No se permite borrar su propio usuario.')
     group = self.get_object().groups.first().name
     current_user_group = self.request.user.groups.first().name
     if not can_delete(
             get_profile_from_name(current_user_group)['id'],
             get_profile_from_name(group)['id']):
         raise NotAcceptable(
             u'No posee autorización para borrar un usuario con perfil \"%s\".'
             % self.get_object().groups.first().name)
     return self.destroy(request, *args, **kwargs)
Esempio n. 30
0
def validate_csv(csv_file):
    if not csv_file:
        msg = 'File is not attached'
        raise NotAcceptable(detail=msg)
    if not csv_file.name.endswith('.csv'):
        msg = 'File is not csv type'
        raise NotAcceptable(detail=msg)

    if csv_file.multiple_chunks():
        msg = "Uploaded file is too big (%.2f MB)." % (csv_file.size /
                                                       (1000 * 1000), )
        raise NotAcceptable(detail=msg)