Django CreditCard Custom field

by Owais Mushtaq

We all are in need of Credit Card fields and how to determine what type of card we have selected, and how we will validate it. Here is a quick example of how you will make Custom Credit Card field with all validations.

class PaymentForm(forms.Form):

  number = CreditCardField(required=True, label=”Card Number”)

  expiration = CCExpField(required=True, label=”Expiration Date”)

  cvc = forms.CharField(required=True, label=”CVV/CVC”,

                        widget=forms.TextInput(attrs={‘size’: ‘3’,

                                                      ‘maxlength’: ‘3’,


  street_address = forms.CharField(required=False, max_length=255,

                            label=”Street Address”,



  state = forms.CharField(required=False, max_length=255,

                          label=mark_safe(“   State”),


  city = forms.CharField(required=False, max_length=255,



  zip = forms.CharField(required=False, max_length=255,

                        label=mark_safe(“   Zip”),



class CreditCardField(forms.IntegerField):

def get_cc_type(self, number):


  Gets credit card type given number. Based on values from Wikipedia page

  “Credit card number”.

  <a href=”



  number = str(number)

  #group checking by ascending length of number

  if len(number) == 13:

    if number[0] == “4”:

      return “Visa”

  elif len(number) == 14:

    if number[:2] == “36”:

      return “MasterCard”

  elif len(number) == 15:

    if number[:2] in (“34”, “37”):

      return “American Express”

  elif len(number) == 16:

    if number[:4] == “6011”:

      return “Discover”

    if number[:2] in (“51”, “52”, “53”, “54”, “55”):

      return “MasterCard”

    if number[0] == “4”:

      return “Visa”

  return “Unknown”


def clean(self, value):


  Check if given CC number is valid and one of the

  card types we accept


  if value and (len(value) < 13 or len(value) > 16):

    raise forms.ValidationError(“Please enter in a valid “+\

        “credit card number.”)

  elif self.get_cc_type(value) not in (“Visa”, “MasterCard”,

      “American Express”, “Discover”):


    raise forms.ValidationError(“Please enter in a Visa, “+\

        “Master Card, Discover, or American Express credit card number.”)

  return super(CreditCardField, self).clean(value)



Leave a Reply

Your email address will not be published. Required fields are marked *

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts