Source code for apps.users.validators

import xml.etree.cElementTree as et  # noqa
from contextlib import suppress

from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.timezone import now

from core.settings import USERS_CONFIGS


[docs] @deconstructible class SVGValidator: message = "This file is not a valid SVG." code = "invalid_svg" def __call__(self, value): # Check file extension if not value.name.endswith(".svg"): raise ValidationError(self.message, code=self.code) # Check file content self._validate_svg_structure(value) def _validate_svg_structure(self, file): """Check SVG structure using xml parsing.""" file.seek(0) tag = None with suppress(et.ParseError): for _, el in et.iterparse(file, ("start",)): tag = el.tag break # Check that this "tag" is correct if tag != "{http://www.w3.org/2000/svg}svg": raise ValidationError(self.message, code=self.code) file.seek(0)
[docs] @deconstructible class AgeValidator: code = "age_validation_error" min_year = 1900 messages = { "age_validation_error": f"The user must be over {USERS_CONFIGS['AGE_LIMIT']} years old.", "min_age_validation_error": f"Year of birth cannot be earlier than {min_year}.", }
[docs] def __init__(self): self.age_limit = USERS_CONFIGS["AGE_LIMIT"]
def __call__(self, value): today = now().date() age = today.year - value.year - ((today.month, today.day) < (value.month, value.day)) if age < self.age_limit: raise ValidationError(self.messages["age_validation_error"], code=self.code) if value.year < self.min_year: raise ValidationError(self.messages["min_age_validation_error"], code=self.code)