Sajib Hossain
Sajib Hossain

Reputation: 81

How can i call own method in django class based api views

I want to create account using phone number as a username and generate otp code . now i want to validate my phone number. I create a method is_phone_valid to validate my phone number but call it by post method but i am getting an error error image This is my views.py

class GetPhoneNumber(CreateAPIView):
    queryset = TempRegistration.objects.all()
    serializer_class = AccountsSerializer

    def is_phone_valid(phone_number):
        if phone_number:
            MOBILE_REGEX = re.compile('^(?:\+?88)?01[15-9]\d{8}$')
            if MOBILE_REGEX.match(phone_number):
                return True
            else:
                return False
        else:
            return False

    def post(self, request, *args, **kwargs):
        return self.is_phone_valid(phone_number)

models.py

class TempRegistration(models.Model):
    phone_number = models.CharField(max_length=45)
    otp_code = models.CharField(max_length=6)

    def __str__(self):
        return self.phone_number

Upvotes: 0

Views: 816

Answers (4)

JPG
JPG

Reputation: 88499

Seems like you are using Django REST Framework. If so, use field-level--DRF doc validation of DRF Serializers, as below

# views.py
class GetPhoneNumber(CreateAPIView):
    queryset = TempRegistration.objects.all()
    serializer_class = AccountsSerializer


# serializers.py
class AccountsSerializer(serializers.ModelSerializer):
    def validate_phone_number(self, phone_number):
        MOBILE_REGEX = re.compile('^(?:\+?88)?01[15-9]\d{8}$')
        if MOBILE_REGEX.match(phone_number):
            return phone_number
        else:
            raise serializers.ValidationError('No. not matching')

    class Meta:
        model = TempRegistration
        fields = '__all__'

Note: You don't need to override the post(...) method of CreateAPIView class.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

If you want to extract the phone number in the POST parameters [wiki], then you should access this in self.request.POST.

Furthermore you can not return a boolean as the result of a request. This needs to be a HttpResponse, for example a JsonResponse object [Django-doc]:

from django.http import JsonResponse

class GetPhoneNumber(CreateAPIView):
    queryset = TempRegistration.objects.all()
    serializer_class = AccountsSerializer

    def is_phone_valid(self, phone_number):
        if phone_number:
            MOBILE_REGEX = re.compile('^(?:\+?88)?01[15-9]\d{8}$')
            if MOBILE_REGEX.match(phone_number):
                return True
            else:
                return False
        else:
            return False

    def post(self, request, *args, **kwargs):
        return JsonResponse(
            {'result': self.is_phone_valid(self.request.POST.get('phone_number'))}
        )

Upvotes: 0

Shibiraj
Shibiraj

Reputation: 769

You have to define the phone_number variable. I hope you're using DRF, then the parameter phone_number will be available in request.data

class GetPhoneNumber(CreateAPIView):
    queryset = TempRegistration.objects.all()
    serializer_class = AccountsSerializer

    def is_phone_valid(phone_number):
        if phone_number:
            MOBILE_REGEX = re.compile('^(?:\+?88)?01[15-9]\d{8}$')
            if MOBILE_REGEX.match(phone_number):
                return True
            else:
                return False
        else:
            return False

    def post(self, request, *args, **kwargs):
        phone_number = request.data['phone_number']
        return Response({'result' : self.is_phone_valid(phone_number)})

Upvotes: 0

Sadan A.
Sadan A.

Reputation: 1107

The traceback you have posted explains that it can't find the phone_number you are passing to self.is_phone_valid(phone_number) in your post method.

Secondly, your question is how to call the is_phone_valid from inside the class? You need to make pass self as the first arg of this method.

class GetPhoneNumber(CreateAPIView):
    queryset = TempRegistration.objects.all()
    serializer_class = AccountsSerializer

    def is_phone_valid(self, phone_number):
        if phone_number:
            MOBILE_REGEX = re.compile('^(?:\+?88)?01[15-9]\d{8}$')
            if MOBILE_REGEX.match(phone_number):
                return True
            else:
                return False
        else:
            return False

    def post(self, request, *args, **kwargs):
        phone_number = request.data['phone_number']
        return self.is_phone_valid(phone_number)

Upvotes: 0

Related Questions