Example #1
0
class WorkDay(models.Model):
    day = models.CharField(
        null=False,
        max_length=9,
        choices=DAYS,
        validators=[
            MinLengthValidator(
                limit_value=6,
                message="Day must be at least 6 characters long."),
            MaxLengthValidator(
                limit_value=9,
                message="Day must be at most 9 characters long."),
            RegexValidator(
                regex="^(Mon|Tues|Wednes|Thurs|Fri|Satur)day$",
                message="Please insert a valid name.",
            ),
            ProhibitNullCharactersValidator(),
        ],
    )
    start_time = models.CharField(
        null=False,
        max_length=8,
        validators=[
            MinLengthValidator(
                limit_value=7,
                message="Start time must be at least 7 characters long.",
            ),
            MaxLengthValidator(
                limit_value=8,
                message="Start time must be at most 8 characters long.",
            ),
            RegexValidator(
                regex="^(1[012]|[1-9]):[0-5]\d [AP]M$",
                message="Please insert a valid start time.",
            ),
            ProhibitNullCharactersValidator(),
        ],
    )
    end_time = models.CharField(
        null=False,
        max_length=8,
        validators=[
            MinLengthValidator(
                limit_value=7,
                message="End time must be at least 7 characters long.",
            ),
            MaxLengthValidator(
                limit_value=8,
                message="End time must be at most 8 characters long.",
            ),
            RegexValidator(
                regex="^(1[012]|[1-9]):[0-5]\d [AP]M$",
                message="Please insert a valid end time.",
            ),
            ProhibitNullCharactersValidator(),
        ],
    )

    class Meta:
        abstract = True
Example #2
0
class Category(models.Model):
    name = models.CharField(max_length=30,
                            null=False,
                            unique=True,
                            validators=[
                                MinLengthValidator(2),
                                MaxLengthValidator(30),
                                RegexValidator("^[A-Za-z,& ]{3,30}$"),
                                ProhibitNullCharactersValidator()
                            ])
    description = models.CharField(
        max_length=250,
        null=False,
        validators=[
            MinLengthValidator(1),
            MaxLengthValidator(250),
            RegexValidator(regex="^[^;]{1,250}$",
                           message="Semicolons are not allowed."),
            ProhibitNullCharactersValidator()
        ])

    def __str__(self):
        return f"Category {self.id}: {self.name}"

    def get_absolute_url(self):
        return reverse("inventory:category_list")

    class Meta:
        verbose_name_plural = "Categories"
        ordering = ("name", )
Example #3
0
class Item(models.Model):
    name = models.CharField(
        max_length=50,
        null=False,
        validators=[
            MinLengthValidator(2),
            MaxLengthValidator(50),
            RegexValidator("^[A-Za-z0-9,'%&:\-\.\(\) ]{2,50}$"),
            ProhibitNullCharactersValidator()
        ])
    weight = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        null=False,
        default=1,
        validators=[MinValueValidator(0.01),
                    MaxValueValidator(5000)])
    price = models.DecimalField(
        max_digits=7,
        decimal_places=2,
        null=False,
        default=0,
        validators=[MinValueValidator(0),
                    MaxValueValidator(99_999.99)])
    description = models.CharField(
        max_length=250,
        null=False,
        validators=[
            MinLengthValidator(1),
            MaxLengthValidator(250),
            RegexValidator(regex="^[^;]{1,250}$",
                           message="Semicolons are not allowed."),
            ProhibitNullCharactersValidator()
        ])
    quantity = models.IntegerField(
        null=False,
        default=0,
        validators=[MinValueValidator(0),
                    MaxValueValidator(100)])
    category = models.ForeignKey(Category,
                                 null=True,
                                 on_delete=models.SET_NULL)

    def __str__(self):
        return f"Item ID {self.id}: {self.name} (${self.price})"

    def get_absolute_url(self):
        return reverse("inventory:item_detail", args=(self.id, ))
Example #4
0
class MenuItem(models.Model):
    name = models.CharField(
        null=False,
        max_length=50,
        validators=[
            MinLengthValidator(
                limit_value=3,
                message="Name must be at least 3 characters long.",
            ),
            MaxLengthValidator(
                limit_value=50,
                message="Name must be at most 50 characters long.",
            ),
            RegexValidator(
                regex="^[A-Za-z0-9 //,'-]{3,50}$",
                message="Please insert a valid name.",
            ),
            ProhibitNullCharactersValidator(),
        ],
    )
    vegan = models.BooleanField(null=False, default=False)
    price = models.DecimalField(
        max_digits=9,
        decimal_places=2,
        null=False,
        default=0,
        validators=[
            MinValueValidator(limit_value=0,
                              message="Please insert a non-negative number."),
            MaxValueValidator(
                limit_value=1_000_000,
                message="Price must not exceed $1 million.",
            ),
        ],
    )
Example #5
0
class Kitchen(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE)
    name = models.CharField(
        null=False,
        max_length=50,
        validators=[
            MinLengthValidator(
                limit_value=2,
                message="Name must be at least 2 characters long.",
            ),
            MaxLengthValidator(
                limit_value=50,
                message="Name must be at most 50 characters long.",
            ),
            RegexValidator(
                regex="^[A-Za-z0-9: ,'&@-]{2,50}$",
                message="Please insert a valid name.",
            ),
            ProhibitNullCharactersValidator(),
        ],
    )
    featured = models.BooleanField(null=False, default=False)
    workdays = models.ArrayField(model_container=WorkDay)
    menu = models.ArrayField(model_container=MenuItem)
    image = models.TextField(max_length=200,
                             blank=True,
                             default="localhost:8000/media/default.jpg")
Example #6
0
    def __init__(self,*args, type=None, request=None,  **kwargs):
        self.type = type
        self.request = request

        super().__init__(*args, **kwargs)
        null = ProhibitNullCharactersValidator()
        print(null)
        self.fields['question'].validators.remove(null)
        self.fields['answer'].validators.remove(null)
Example #7
0
 def test_prohibit_null_characters_validator_equality(self):
     self.assertEqual(
         ProhibitNullCharactersValidator(message='message', code='code'),
         ProhibitNullCharactersValidator(message='message', code='code'))
     self.assertEqual(ProhibitNullCharactersValidator(),
                      ProhibitNullCharactersValidator())
     self.assertNotEqual(
         ProhibitNullCharactersValidator(message='message1', code='code'),
         ProhibitNullCharactersValidator(message='message2', code='code'))
     self.assertNotEqual(
         ProhibitNullCharactersValidator(message='message', code='code1'),
         ProhibitNullCharactersValidator(message='message', code='code2'))
Example #8
0
 def __init__(self, inherit_color=False, default_color=DEFAULT_COLOR, *args, **kwargs):
     kwargs.pop('required', None)
     with_alpha = kwargs.pop('with_alpha', app_settings.CMSPLUGIN_CASCADE['color_picker_with_alpha'])
     widget = kwargs.pop('widget', ColorPickerWidget(with_alpha))
     fields = [
         CharField(initial=default_color),
         BooleanField(initial=inherit_color, required=False),
     ]
     kwargs['initial'] = [default_color, inherit_color]
     super().__init__(fields=fields, widget=widget, *args, **kwargs)
     self.validators.append(ColorValidator(with_alpha))
     if DJANGO_VERSION >= (2, 0):
         self.validators.append(ProhibitNullCharactersValidator())
Example #9
0
 def test_prohibit_null_characters_validator_equality(self):
     self.assertEqual(
         ProhibitNullCharactersValidator(message="message", code="code"),
         ProhibitNullCharactersValidator(message="message", code="code"),
     )
     self.assertEqual(
         ProhibitNullCharactersValidator(), ProhibitNullCharactersValidator()
     )
     self.assertNotEqual(
         ProhibitNullCharactersValidator(message="message1", code="code"),
         ProhibitNullCharactersValidator(message="message2", code="code"),
     )
     self.assertNotEqual(
         ProhibitNullCharactersValidator(message="message", code="code1"),
         ProhibitNullCharactersValidator(message="message", code="code2"),
     )
Example #10
0
class MultipleStringField(forms.TypedMultipleChoiceField):
    """
    Field that does not validate if the field values are in self.choices

    Validators are run on each item in the list, rather than against the whole input,
    like other Django fields.
    """

    default_validators = [ProhibitNullCharactersValidator()]

    def valid_value(self, value):
        """
        Run validators on each item in the list.

        The TypedMultipleChoiceField.valid_value method checks that
        the string is in self.choices, and this version explictly skips that check.
        """
        self.run_validators(value)
        return True
Example #11
0
          '+Inf',
          'Infinity',
          '-Infinity',
          '-Infinity',
      )],
    (validate_image_file_extension, ContentFile('contents',
                                                name='file.jpg'), None),
    (validate_image_file_extension, ContentFile('contents',
                                                name='file.png'), None),
    (validate_image_file_extension, ContentFile('contents',
                                                name='file.PNG'), None),
    (validate_image_file_extension, ContentFile('contents', name='file.txt'),
     ValidationError),
    (validate_image_file_extension, ContentFile('contents',
                                                name='file'), ValidationError),
    (ProhibitNullCharactersValidator(), '\x00something', ValidationError),
    (ProhibitNullCharactersValidator(), 'something', None),
    (ProhibitNullCharactersValidator(), None, None),
]


def create_path(filename):
    return os.path.abspath(os.path.join(os.path.dirname(__file__), filename))


# Add valid and invalid URL tests.
# This only tests the validator without extended schemes.
with open(create_path('valid_urls.txt'), encoding='utf8') as f:
    for url in f:
        TEST_DATA.append((URLValidator(), url.strip(), None))
with open(create_path('invalid_urls.txt'), encoding='utf8') as f:
Example #12
0
 def __init__(self, *, allowed_units=None, **kwargs):
     self.empty_value = ''
     super().__init__(**kwargs)
     self.validators.append(SizeUnitValidator(allowed_units))
     self.validators.append(ProhibitNullCharactersValidator())
Example #13
0
        )
    ],
    (validate_image_file_extension, ContentFile("contents", name="file.jpg"), None),
    (validate_image_file_extension, ContentFile("contents", name="file.png"), None),
    (validate_image_file_extension, ContentFile("contents", name="file.PNG"), None),
    (
        validate_image_file_extension,
        ContentFile("contents", name="file.txt"),
        ValidationError,
    ),
    (
        validate_image_file_extension,
        ContentFile("contents", name="file"),
        ValidationError,
    ),
    (ProhibitNullCharactersValidator(), "\x00something", ValidationError),
    (ProhibitNullCharactersValidator(), "something", None),
    (ProhibitNullCharactersValidator(), None, None),
]

# Add valid and invalid URL tests.
# This only tests the validator without extended schemes.
TEST_DATA.extend((URLValidator(), url, None) for url in VALID_URLS)
TEST_DATA.extend((URLValidator(), url, ValidationError) for url in INVALID_URLS)


class TestValidators(SimpleTestCase):
    def test_validators(self):
        for validator, value, expected in TEST_DATA:
            name = (
                validator.__name__
Example #14
0
class User(AbstractUser):
    phone_number = models.CharField(
        max_length=12,
        null=False,
        validators=[
            RegexValidator(
                regex="^\d{3}-\d{3}-\d{4}(-\d{2,6})?$",
                message="Please enter a valid phone number. (XXX-XXX-XXXX)")
        ])
    address = models.CharField(
        max_length=40,
        null=False,
        validators=[
            RegexValidator(regex="^\d{1,5} [a-zA-Z0-9\. ]+$",
                           message="Please enter a valid street address.")
        ])
    city = models.CharField(max_length=25,
                            null=False,
                            validators=[
                                RegexValidator(
                                    regex="^[a-zA-Z\. -']+$",
                                    message="Please enter a valid city name.")
                            ])
    state = models.CharField(max_length=20, null=False, choices=US_STATES)
    zip_code = models.CharField(
        max_length=10,
        null=False,
        validators=[
            RegexValidator(regex="^\d{5}(-\d{4})?$",
                           message="Please enter a valid ZIP code.")
        ])
    question_one = models.CharField(
        null=False,
        max_length=80,
        choices=SECURITY_QUESTIONS,
        validators=[
            MinLengthValidator(
                limit_value=20,
                message="Security question must be at least 20 characters long."
            ),
            MaxLengthValidator(
                limit_value=80,
                message="Security question must be at most 80 characters long."
            ),
            RegexValidator(regex="^[A-Za-z0-9 ,'//]{20,80}\?$",
                           message="Please insert a valid security question."),
            ProhibitNullCharactersValidator()
        ])
    answer_one = models.CharField(
        null=False,
        max_length=50,
        validators=[
            MinLengthValidator(
                limit_value=2,
                message="Answer must be at least 2 characters long."),
            MaxLengthValidator(
                limit_value=80,
                message="Answer must be at most 50 characters long."),
            RegexValidator(regex="^[A-Za-z0-9 ,'-:\?]{2,50}$",
                           message="Please insert a valid answer."),
            ProhibitNullCharactersValidator()
        ])
    question_two = models.CharField(
        null=False,
        max_length=80,
        choices=SECURITY_QUESTIONS,
        validators=[
            MinLengthValidator(
                limit_value=20,
                message="Security question must be at least 20 characters long."
            ),
            MaxLengthValidator(
                limit_value=80,
                message="Security question must be at most 80 characters long."
            ),
            RegexValidator(regex="^[A-Za-z0-9 ,'//]{20,}\?$",
                           message="Please insert a valid security question."),
            ProhibitNullCharactersValidator()
        ])
    answer_two = models.CharField(
        null=False,
        max_length=50,
        validators=[
            MinLengthValidator(
                limit_value=2,
                message="Answer must be at least 2 characters long."),
            MaxLengthValidator(
                limit_value=80,
                message="Answer must be at most 50 characters long."),
            RegexValidator(regex="^[A-Za-z0-9 ,'-:\?]{2,50}$",
                           message="Please insert a valid answer."),
            ProhibitNullCharactersValidator()
        ])
    objects = KitchenUserManager()