Esempio n. 1
0
 def test_create(self):
     data = {
         'username': '******',
         'email': '*****@*****.**',
         'password': '******',
         'max_backups': 7
     }
     serializer = AccountSerializer(data=data)
     serializer.create(data)
     account = Account.objects.get(pk='test_username1')
     self.assertEqual(account.email, data['email'])
     self.assertEqual(account.username, data['username'])
     self.assertEqual(account.max_backups, data['max_backups'])
     self.assertTrue(account.check_password('test_password1'))
Esempio n. 2
0
def accounts_add(request):
    """
        Function to manage the addition of new accounts
    """
    # Creating the default value
    response = {}

    # If not declared in settings, configuring a default value
    # http://www.django-rest-framework.org/api-guide/exceptions/#exception-handling-in-rest-framework-views
    try:
        nfe = settings.NON_FIELD_ERRORS_KEY
    except AttributeError:
        nfe = 'non_field_errors'

    # Parsing data from the request and changing the creator field for the user who did the request
    data = JSONParser().parse(request)
    data['creator'] = request.user.pk

    # Check if all the data is valid to be used
    serializer = AccountSerializer(data=data)
    if serializer.is_valid():
        # If valid, create it and notify
        try:
            Account.objects.get(iban=serializer.validated_data['iban'])
            response = {
                'errors': {
                    nfe: 'iban already exists',
                }
            }
            return Response(response, status=status.HTTP_400_BAD_REQUEST)

        except Account.DoesNotExist:
            serializer.create(serializer.validated_data)
            response = {
                'status': 'ok',
                'message': 'created'
            }
            return Response(response, status=status.HTTP_201_CREATED)
    else:
        # If not valid, raise an error for data_validation
        response = {
            {'errors': {'data_validation_error': 'Error validating data'}}
        }
        return Response(response, status=status.HTTP_400_BAD_REQUEST)