Advertisement
horozov86

4. Credit Card Masking

Nov 21st, 2023
2,555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.76 KB | None | 0 0
  1. class MaskedCreditCardField(models.CharField):
  2.     def __init__(self, *args, **kwargs):
  3.         kwargs['max_length'] = 20
  4.         super().__init__(*args, **kwargs)
  5.        
  6.     def to_python(self, value):
  7.         if not isinstance(value, str):
  8.             raise ValidationError("The card number must be a string")
  9.            
  10.         if not value.isdigit():
  11.             raise ValidationError("The card number must contain only digits")
  12.            
  13.         if len(value) != 16:
  14.             raise ValidationError("The card number must be exactly 16 characters long")
  15.            
  16.         return f"****-****-****-{value[-4:]}"
  17.            
  18. class CreditCard(models.Model):
  19.     card_owner = models.CharField(max_length=100)
  20.     card_number - MaskedCreditCardField()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement