Ahmad Mardene
Ahmad Mardene

Reputation: 47

make length in integerfield django model

my model.py is :

from django.core.validators import MinLengthValidator,MaxLengthValidator

    class clients(models.Model):
        client_identity_id = models.IntegerField(validators=[MaxLengthValidator(11),MinLengthValidator(11)], unique=True)

        '
        '

my serializers.py is :

class UserSerializer(serializers.ModelSerializer):
    #money = serializers.IntegerField(required=False)
    class Meta:
        model = clients
        fields = ('client_identity_id','client_id','client_firstname','client_middlename','client_lastname','client_country','money','client_num')
        read_only_fields = ('money','client_id')
    def create(self, validated_data, **kwargs):
        validated_data['client_id'] = ''.join(secrets.choice(string.ascii_uppercase + string.digits) 
                                              for i in range(8))

        return clients.objects.create(**validated_data)

my views.py is :

def post(self,request):
    data=request.data
    serializer = UserSerializer(data=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)

but when i make a post request with client_identity_id=12345678910 it keep telling me "object of type 'int' has no len()" how can i fix that please ?

Upvotes: 2

Views: 1546

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

A digit with 11 digits ranges between 10000000000 and 99999999999, so you can work with:

from django.core.validators import MinValueValidator, MaxValueValidator

class clients(models.Model):
        client_identity_id = models.IntegerField(
            validators=[
                MinValueValidator(10_000_000_000),
                MaxValueValidator(99_999_999_999)
            ],
            unique=True
        )

Upvotes: 1

wgarlock
wgarlock

Reputation: 116

The error you’re receiving is a python error. Integers are not iterable objects in python. I assume your validators rely on the len() method which only works on iterable objects (strings, lists, etc.) I recommend you change your field to a CharField() or create a custom validator to check the scientific notation value of your integer. Example. An 11 character like 10000000000 would be 1 x 10^11. Hint the exponent is 11 here. I hope this helps!

Upvotes: 0

Related Questions