What was done
I have a form that receives a code that is given to the user so he can verify his email address. To check if the form is valid I created a custom field validator, see forms.py
Problem
It looks like if raise ValidationError("...")
would always fail in the try
-block. Is this normal behavior or did I something wrong?
forms.py
class SignUpVerificationForm(forms.Form):
def is_valid_verification_code(code):
#settings
time_to_verify_in_minutes = 5
try:
tmp = SignUpUser.objects.get(signup_verification=code)
email = tmp.signup_email
time = tmp.signup_time
if time >= timezone.now() - datetime.timedelta(minutes=time_to_verify_in_minutes):
try:
check = User.objects.get(email=email)
raise ValidationError("This verification code was already used.")
except:
return code
else:
raise ValidationError("This verification code has expired.")
except:
raise ValidationError("Invalid verification code.")
verification_code = forms.CharField(max_length=50,
label='',
validators=[is_valid_verification_code]
)
Edit with ugly solution
I ended up with the code below. I think it's not the right way of doing this but i don't know better at the moment and it's working
def is_valid_verification_code(code):
#settings
time_to_register_in_minutes = 5
try:
tmp = SignUpUser.objects.get(signup_verification=code)
email = tmp.signup_email
time = tmp.signup_time
if time >= timezone.now() - datetime.timedelta(minutes=time_to_register_in_minutes):
try:
user_already_active = User.objects.get(email=email)
user_already_active = 1
except:
return code
else:
try:
user_already_active = User.objects.get(email=email)
user_already_active = 1
except:
user_already_active = 0
except:
raise ValidationError("Invalid verification code.")
if user_already_active:
raise ValidationError("This verification code was already used.")
if not user_already_active:
raise ValidationError("This verification code has expired.")