我通过电话号码注册用户作为用户名。当我输入电话号码时,会生成一个otp号码并将其保存在数据库中。我已经生成了选择号,但我无法保存它。那么,我该如何保存呢?
我的serializers.py文件
class AccountsSerializer(serializers.ModelSerializer):
def validate_phone_number(self, phone_number):
if phone_number:
MOBILE_REGEX = re.compile('^(?:\+?88)?01[13-9]\d{8}$')
if MOBILE_REGEX.match(phone_number):
return (phone_number)
else:
raise serializers.ValidationError('No. not matching')
else:
raise serializers.ValidationError('Please enter a number')
def generate_otp(self):
otp = randint(000000, 999999)
return otp
class Meta:
model = TempRegistration
fields = ['phone_number']
views.py
class GetPhoneNumber(CreateAPIView):
queryset = TempRegistration.objects.all()
serializer_class = AccountsSerializer
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
答案 0 :(得分:2)
覆盖 perform_create(...)
视图的 GetPhoneNumber
方法
class GetPhoneNumber(CreateAPIView):
queryset = TempRegistration.objects.all()
serializer_class = AccountsSerializer
def perform_create(self, serializer):
serializer.save(otp_code=randint(000000, 999999))