Skip to content

Instantly share code, notes, and snippets.

@joncombe
Last active May 8, 2021 07:19
Show Gist options
  • Save joncombe/e9ee60f3c7ba331168a504ce1626f2c8 to your computer and use it in GitHub Desktop.
Save joncombe/e9ee60f3c7ba331168a504ce1626f2c8 to your computer and use it in GitHub Desktop.
Django IntegerCSVField: Accepts a string such as "43,575,3,123,543". Any other characters are invalid
from django import forms
from django.core.exceptions import ValidationError
from apps.merchant.models import Merchant
from views.form_fields import XEDateRangeField
class IntegerCSVField(forms.CharField):
def __init__(self, min_value=None, max_value=None, *args, **kwargs):
super().__init__(**kwargs)
self.min_value = min_value
self.max_value = max_value
def clean(self, value):
# check a valid list of integers separated by commas
# nothing else is allowed
try:
values = [int(i) for i in value.split(',')]
except:
raise ValidationError('Non-integers found')
# check in bounds
if self.min_value:
for i in values:
if i < self.min_value:
raise ValidationError('Number below min_value found')
if self.max_value:
for i in values:
if i > self.max_value:
raise ValidationError('Number above max_value found')
# ok
return values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment