Add Custom Error

Report a typo

You have a form for using a promo code in an online shop:

class PromoCodeForm(forms.Form):
    user = forms.CharField()
    code = forms.CharField(min_length=16, max_length=16)

Write a function to add custom errors to the form if needed. The result should satisfy the following conditions:

  • If the form is already invalid, do not add any new errors
  • If the code doesn't start with the current year, add "promo code is expired" error to code field
  • If the code doesn't end with the word "django", add "checksum is invalid" error to code field

The variable current_year is already defined, so you don't have to import datetime module and get the current year yourself.

Write a program in Python 3
def add_custom_errors(promo_code_form):
code_data = promo_code_form.data.get('code')
...
___

Create a free account to access the full topic