(S) Validators

Validators

Przykładowe zastosowanie

Regex validator

Django models.py:

# Validators Import:
from .validators import ColorValidator

# Additional device model:
class Tag(models.Model):
    # Validators:
    color_validator = ColorValidator()
    # Model values:
    name = models.CharField(max_length=32, blank=False, unique=True)
    color = models.CharField(
        max_length=8,
        blank=True,
        null=True,
        validators=[color_validator],
    )
Django validators.py:

# Django Import:
from django.utils.deconstruct import deconstructible
from django.core import validators

@deconstructible
class ColorValidator(validators.RegexValidator):
    regex = r'^#([0-9,A-F,a-f]{3}|[0-9,A-F,a-f]{6})$'
    message = "Message"
    flags = 0

Raise Error validator

Django models.py:

# Validators Import:
from .validators import validate_even

# Additional device model:
class Tag(models.Model):
    color = models.CharField(validators=[validate_even])
Django forms.py:

# Validators Import:
from .validators import validate_even

# Additional device model:
class TagForm(forms.Form):
    even_field = forms.IntegerField(validators=[validate_even])
Django validators.py:

from django.core.exceptions import ValidationError

def validate_even(value):
    if value % 2 != 0:
        raise ValidationError(
            '%(value)s is not an even number',
            params={'value': value},
        )
PDFPRINT

Robert T Kucharski

Cisco Network Engineer in GPW.

Dodaj komentarz