Example #1
0
class ChainSerializer(serializers.ModelSerializer):
    account = AccountSerializer(read_only=True)
    tags = HashtagSerializer(
        many=True,
        read_only=True
    )
    mentions = AccountSerializer(
        many=True,
        read_only=True,
    )
    likes = AccountSerializer(
        many=True,
        read_only=True,
    )

    class Meta:
        model = Chain
        fields = (
            'id',
            'account',
            'text',
            'image',
            'tags',
            'mentions',
            'likes',
            'parent_chain',
            'child_chains',
            'created_at',
        )
        read_only_fields = (
            'child_chains',
        )
        extra_kwargs = {
            'account': {'write_only': True}
        }
Example #2
0
    def patch(self, req, pk):
        if req.user.pk != int(pk) and not req.user.is_superuser:
            return Response(status=status.HTTP_401_UNAUTHORIZED,
                            data={'reason': 'User account is not authorized'})

        try:
            acc = Account.objects.get(id=pk)
            serializer = AccountSerializer(acc, data=req.data, partial=True)
            if serializer.is_valid():
                serializer.save()
        except Account.DoesNotExist:
            return Response(
                status=status.HTTP_404_NOT_FOUND,
                data={'reason': 'User account not found for the requested pk'})

        if req.user.is_superuser:
            acc_data = serializer.data
        else:
            acc_data = {
                'id': serializer.data['id'],
                'username': serializer.data['username'],
                'first_name': serializer.data['first_name'],
                'last_name': serializer.data['last_name'],
                'email': serializer.data['email'],
                'profile_pic': serializer.data['profile_pic']
            }

        return Response(status=status.HTTP_202_ACCEPTED, data=acc_data)
Example #3
0
 def put(self, request, pk, format=None):
     account = get_object_or_404(Account, pk=pk)
     serializer = AccountSerializer(account, data=request.DATA)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #4
0
    def get(self, request):
        accounts = get_user_model().objects.all()

        id = request.query_params.get('id')
        sort = request.query_params.get(ORDERING_PARAM)
        account_type = request.query_params.get('account_type')

        if id:
            accounts = accounts.filter(pk=id)
        if account_type == 'admin':
            accounts = accounts.filter(is_admin=True)
        elif account_type == 'teacher':
            accounts = accounts.filter(teacher__isnull=False).distinct()
        elif account_type == 'student':
            accounts = accounts.filter(student__isnull=False).distinct()

        if sort:
            accounts = accounts.order_by(f'{sort}')

        serializer = AccountSerializer(accounts, many=True)
        page = self.paginate_queryset(accounts)
        if page is not None:
            serializer = self.get_paginated_response(
                AccountSerializer(page, many=True).data)

        return Response(serializer.data, status=status.HTTP_200_OK)
Example #5
0
    def post(self, request):
        serializer = AccountSerializer(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)
Example #6
0
 def post(self, request):
     data = request.data
     serializer = AccountSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=400)
class TaskSerializer(serializers.ModelSerializer):
    requestee_details = AccountSerializer(source='requestee', read_only=True)
    volunteer_details = AccountSerializer(source='volunteer', read_only=True)
    requested_vol_details = AccountSerializer(source='requested_vol',
                                              read_only=True)
    task_type_details = TaskTypeSerializer(source='task_type', read_only=True)
    status_name = serializers.CharField(source='get_status_display',
                                        read_only=True)
    distance = serializers.SerializerMethodField(
        'get_distance_between_vol_and_vul')
    expired = serializers.SerializerMethodField()

    def get_distance_between_vol_and_vul(self, Task):
        volunteer = self.context.get("logged_in_volunteer", None)
        if volunteer:
            volunteer_location = volunteer.location
            return round(
                (volunteer_location.distance(Task.requestee.location)) * 100,
                2)
        else:
            return None

    def get_expired(self, obj):
        return obj.end_time <= datetime.now(timezone.utc)

    class Meta:
        model = Task
        fields = ("id", "task_type", "task_type_details", "description",
                  "dbs_required", "start_time", "end_time", "status",
                  "status_name", "expired", "requestee", "volunteer",
                  "requested_vol", "requestee_details", "volunteer_details",
                  "requested_vol_details", "distance")
Example #8
0
 def post(self, request, format=None):
     account_serializer = AccountSerializer(data=request.data)
     if account_serializer.verify_balance(account_serializer):
         account_serializer.save()
         return Response(account_serializer.data,
                         status=status.HTTP_201_CREATED)
     return Response(account_serializer.errors,
                     status=status.HTTP_400_BAD_REQUEST)
Example #9
0
 def put(self, request, pk, format=None):
     account = self.get_object(pk)
     account_serializer = AccountSerializer(account, data=request.data)
     if account_serializer.verify_balance(account_serializer):
         account_serializer.save()
         return Response(account_serializer.data)
     return Response(account_serializer.errors,
                     status=status.HTTP_400_BAD_REQUEST)
Example #10
0
 def post(self, request, format='json'):
     serializer = AccountSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.save()
         if user:
             json = serializer.data
             return Response(json, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #11
0
	def get(self, request, user=None):
		if request.user.username == user:
			user = None
		
		self_profile = False

		if user is not None:
			user = user.replace('-', ' ')

			try:
				account = UserAccount.objects.get(username=user)
				self_profile = False
			except:
				return Response({
					'message': 'Username ' + user + ' does not exist.',
				}, status=status.HTTP_404_NOT_FOUND)
		else:
			account = request.user
			self_profile = True
			if isinstance(account, AnonymousUser):
				return Response({
					'success': 'no',
					'message': 'User unauthorized to make the request.'
				}, status=status.HTTP_403_FORBIDDEN)

		serialized = AccountSerializer(account)
		serialized = dict(serialized.data)  #no need to validate as it is surely a UserAccount instance
		
		try:
			path = serialized['profile_image'].split('TopBargain/')[1]
		except:
			path = ''

		serialized['profilePic'] = path			
		serialized.pop('profile_image')

		print(request.user.username)

		if self_profile:
			serialized['isSelfProfile'] = True
		else:
			serialized['isSelfProfile'] = False

		serialized['posts'] = []
		posts = PostModel.objects.filter(username=account).order_by('-postDate')

		for post in posts:
			serialized_post = PostSerializer(post)
			serialized_post = dict(serialized_post.data)
			
			try:
				serialized_post['image'] = serialized_post['image'].split('TopBargain/')[1] #to get the static URL
			except:
				serialized_post['image'] = None

			serialized['posts'].append(serialized_post)

		return Response(serialized)
Example #12
0
 def put(self, request, pk, format=None):
     account = self.get_object(pk)
     serializer = AccountSerializer(account,
                                    data=request.data,
                                    partial=True)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #13
0
def account_list(request):
    if request.method == 'GET':
        accounts = Account.objects.all()
        accounts_serializer = AccountSerializer(accounts, many=True)
        return Response(accounts_serializer.data)

    elif request.method == 'POST':
        accounts_serializer = AccountSerializer(data=request.data)
        if accounts_serializer.is_valid():
Example #14
0
    def test_user_serializer_create_positive(self):
        s = AccountSerializer()

        user = s.create(
            validated_data={
                "email": self.email,
                "first_name": self.first_name,
                "last_name": "Last Name",
                "username": "******",
                "password": self.password,
            })
        self.assertIsInstance(user, User)
Example #15
0
def sign_up(request):
    serializer = AccountSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)

    find_one = Tenant.objects.filter(schema_name=request.data.get('username'))
    if find_one.first():
        return Response(status=HTTP_400_BAD_REQUEST,
                        data=_('this username is already exists'))

    create_account(data=request.data)
    send_log_in_email(email=request.data.get('email'))
    return Response(status=HTTP_201_CREATED,
                    data=_('account created login next'))
Example #16
0
def account_list(request):
    context = {'request': request}

    if request.method == 'GET':
        serializer = AccountSerializer(Account.objects.all(), many=True, context=context)
        return Response(serializer.data, status=status.HTTP_200_OK)

    if request.method == 'POST':
        form = AccountCreationForm(data=request.POST)
        if form.is_valid():
            account = form.save()
            serializer = AccountSerializer(instance=account, context=context)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(form.errors.as_json(), status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Example #17
0
    def test_update_account(self):
        """Order data is updated correctly for users."""
        account = AccountFactory(status="ACTIVE")
        serializer = AccountSerializer(
            account,
            data={"status": "APPROVAL_PENDING"},
            partial=True,
            context={"request": self.request},
        )

        self.assertTrue(serializer.is_valid())
        serializer.save()

        account.refresh_from_db()
        self.assertEqual(account.status, "APPROVAL_PENDING")
Example #18
0
def sendMoney(request):
    amount = request.POST.get('amount')
    senderId = request.POST.get('senderId')
    recieverId = request.POST.get('recieverId')
    senderAccountId = request.POST.get('senderAccountId')
    recieverAccountId = request.POST.get('recieverAccountId')


    print('reciever Id*********************' , recieverAccountId)
    print('sender Id*************************' , senderAccountId)
    try:
        sender = Customer.objects.get(id = senderId)
        reciever = Customer.objects.get(id = recieverId)

    except Customer.DoesNotExist:
        return Response('No user found ', status= status.HTTP_204_NO_CONTENT)
    senderAccount = Account.objects.get(account_number = senderAccountId, customer_id = sender)
    recieverAccount = Account.objects.get(account_number = recieverAccountId, customer_id = reciever)

    senderAccount.balance = senderAccount.balance - float(amount)
    recieverAccount.balance = recieverAccount.balance + float(amount) 

    senderAccount.save()
    recieverAccount.save()

    serializer = AccountSerializer(senderAccount)
    return Response(serializer.data, status= status.HTTP_200_OK)
class UserSerializer(serializers.ModelSerializer):
    accounts = AccountSerializer(many=True)
    memberships = MembershipShortSerializer(many=True, source='membership_set')

    class Meta:
        model = User
        fields = ['id', 'email', 'accounts', 'memberships']
Example #20
0
class EventSerializer(serializers.ModelSerializer):
    organizer = AccountSerializer(read_only=True)

    class Meta:
        model = Event
        fields = ('id', 'name', 'description', 'time', 'topic',
                  'capacity', 'campus', 'organizer')
Example #21
0
class CloudSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    timestamp = serializers.DateTimeField(read_only=True)
    user = AccountSerializer(many=False, read_only=True)

    type = serializers.ChoiceField(choices=TYPE_CHOICES)
    position = GeometryField()
    body = serializers.CharField(max_length=400,
                                 validators=[word_filter_validator])

    code = serializers.CharField(required=False,
                                 allow_null=True,
                                 allow_blank=True,
                                 max_length=20,
                                 validators=[word_filter_validator])
    stars = serializers.IntegerField(required=False, allow_null=True)
    expiry = serializers.IntegerField(required=False, allow_null=True)

    votes = VoteSerializer(many=True, read_only=True)

    def create(self, validated_data):
        instance = Cloud.objects.create(**validated_data,
                                        user=self.context['user'])
        instance.save()
        return instance

    class Meta:
        model = Cloud
        exclude = ('visible', )
Example #22
0
class MessagesSerializer(serializers.ModelSerializer):
    account = AccountSerializer()

    class Meta:
        model = Messages
        fields = ('account', 'message', 'created', 'updated')
        read_only_fields = ('account', 'message', 'created', 'updated')
Example #23
0
    def post(self, request, *args, **kwargs):
        """
        Authenticate user
        :param request: request made by the user
        :return: Response object with account data
        """
        data = request.data
        email = data.get('email')
        password = data.get('password')

        try:
            account = Account.objects.get(email__iexact=email)
            authenticated_account = authenticate(email=account.email, password=password)

            if authenticated_account:
                login(request, authenticated_account)
                serialized_account = AccountSerializer(authenticated_account)
                data = serialized_account.data
                return response.Response(data)

        except Account.DoesNotExist:
            pass

        return response.Response({
            'status': 'Unauthorized',
            'message': 'Email/password combination invalid'
        }, status=status.HTTP_401_UNAUTHORIZED)
Example #24
0
class ApplicationSerializer(serializers.ModelSerializer):
    entries = ApplicationEntrySerializer(many=True)
    contract = ContractSerializer(source='get_contract', read_only=True)
    account = AccountSerializer(source='get_account', read_only=True)
    order = OrderSerializer(source='get_order', read_only=True)
    client = serializers.PrimaryKeyRelatedField(queryset=Client.objects.all(),
                                                allow_null=True)

    class Meta:
        model = Application
        fields = 'id', 'date', 'type', 'client', 'entries', 'contract', 'account', 'order'  # , 'protocols',

    def create(self, validated_data):
        entries = validated_data.pop('entries')
        if validated_data['client'] is None:
            validated_data['client'] = Client.objects.create(
                short_name='<без названия>')
        application = Application.objects.create(**validated_data)
        for entry in entries:
            ApplicationEntry.objects.create(application=application, **entry)
        return application

    def update(self, instance: Application, validated_data):
        ApplicationEntry.objects.filter(application=instance).delete()
        entries = validated_data.pop('entries')
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        for entry in entries:
            ApplicationEntry.objects.create(application=instance, **entry)
        instance.save()
        return instance
Example #25
0
class OnlineUsersSerializer(serializers.ModelSerializer):
    account = AccountSerializer()

    class Meta:
        model = OnlineUsers
        fields = ('account', 'is_online')
        read_only_fields = ('account', 'is_online')
Example #26
0
    def post(self, request):
        data = json.loads(request.body)
        #load JSON data from request and convert to python dict
        serialized = AccountSerializer(data=data)
        print(request.data)

        if serialized.is_valid():
            UserAccount.objects.create_user(**serialized.validated_data)
            return Response({
                'isRegistered': 'yes',
                'message': 'Registration Successful.'
            })

        return Response(
            {'message': 'Account could not be created with received data.'},
            status=status.HTTP_400_BAD_REQUEST)
Example #27
0
def register_api(request):
    if request.method == 'GET':
        return Response({"data": "You wanna register a new user"})
    elif request.method == 'POST':
        data = request.data

        if request.data.get("password") != request.data.get("password1"):
            return Response({"error": "Please enter same password"})
        else:
            if len(request.data.get("password")) < 5:
                return Response({
                    "error":
                    "please enter a password more than 5 characters"
                })

            data = {
                "email": request.data.get("email"),
                "username": request.data.get("username"),
                "first_name": request.data.get("first_name"),
                "last_name": request.data.get("last_name"),
                "password": request.data.get("password")
            }

            account = AccountSerializer().create(data)

            return Response({"user": account})
Example #28
0
 def test_guest_list(self):
     accounts = AccountFactory.create_batch(5)
     guest_list = list(
         map(lambda acc: AccountSerializer(acc).data, accounts))
     event = EventSerializer(EventFactory.create(attendees=accounts)).data
     url = self.get_collection_url(event['id'])
     res = self.client.get(url)
     self.assertEqual(res.json()['results'], guest_list)
Example #29
0
    def test_get_for_list_of_accounts(self):
        self.populate_accounts()
        AccountTestFactory.create_batch(3)
        accs = list(Account.objects.all())

        request = self.req_fact.get('/accounts/')
        resp = resolve('/accounts/').func(request)
        self.assertEqual(AccountSerializer(accs, many=True).data, resp.data)
def account_list(request):
    if request.method == 'GET':
        # faz uma lista com todos os Account
        accounts = Account.objects.all()
        # faz a serialização (Model -> JSON)
        # o many=True serve para serializar uma lista de objetos
        # em vez de uma única instância de objeto
        accounts_serializer = AccountSerializer(accounts, many=True)
        return Response(accounts_serializer.data)

    elif request.method == 'POST':
        if AccountSerializer(data=request.data).validate_json_creation_date(
                request.data):
            # faz a deserialização (JSON -> Model) passando os dados necessários
            account_serializer = AccountSerializer(data=request.data)
            # salva o account caso seja válido, depois
            # retorna account_serializer.data e 201
            if account_serializer.is_valid():
                account_serializer.save()
                return Response(account_serializer.data,
                                status=status.HTTP_201_CREATED)

        # account inválido retorna 400
        return Response(account_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Example #31
0
 def post(self, request, format=None):
     serializer = AccountSerializer(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)