class AcessoForm(ModelForm): cpf = RegexField(regex=r'^[0-9]+$', error_messages={ 'invalid_number': 'Por favor insira um CPF válido, somente números.' }, min_length=11) celular = RegexField(regex=r'^[0-9]+$', error_messages={ 'invalid_phonenumber': "Por favor insira somente números. Ex.51999999999" }) senha = RegexField( regex=r'^[0-9]+$', error_messages={'invalid_number': 'Por favor insira 4 dígitos.'}, min_length=4, max_length=4) class Meta: model = cadastro_acesso fields = [ 'nome', 'celular', 'email', 'cpf', 'senha', 'data_ini', 'data_fim', 'foto', 'obs' ]
def test_empty_value(self): f = RegexField("", required=False) self.assertEqual(f.clean(""), "") self.assertEqual(f.clean(None), "") f = RegexField("", empty_value=None, required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None))
def test_empty_value(self): f = RegexField('', required=False) self.assertEqual(f.clean(''), '') self.assertEqual(f.clean(None), '') f = RegexField('', empty_value=None, required=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None))
class AuthorEditProfileForm(ModelForm): attrs_dict = {'class': 'input-xlarge'} bio = CharField( widget=Textarea(attrs=dict(attrs_dict, maxlength=2048, placeholder='Небольшое описание, отображается в профиле')), max_length=2048, label='Пару слов о себе', required=False, ) jabber = EmailField( widget=TextInput(attrs=dict(attrs_dict, maxlength=75, placeholder='Адрес jabber-аккаунта')), max_length=75, label='Jabber ID (XMPP)', error_messages={'invalid': 'Пожалуйста, исправьте ошибку в адресе jabber: похоже, он неправильный'}, required=False, help_text='Пример: [email protected]', ) skype = RegexField( regex=ur'^[a-zA-Z0-9\._-]+$', widget=TextInput(attrs=dict(attrs_dict, maxlength=32, placeholder='Логин skype')), max_length=32, label='Skype ID', error_messages={'invalid': 'Пожалуйста, исправьте ошибку в логине skype: похоже, он неправильный'}, required=False ) tabun = RegexField( regex=ur'^[a-zA-Z0-9-_]+$', widget=TextInput(attrs=dict(attrs_dict, maxlength=32)), max_length=32, label='Логин на Табуне', error_messages={'invalid': 'Пожалуйста, исправьте ошибку в имени пользователя: похоже, оно неправильно'}, required=False ) forum = URLField( widget=TextInput(attrs=dict(attrs_dict, maxlength=32, placeholder='URL вашего профиля')), max_length=72, label='Профиль на Форуме', help_text='Вставьте полную ссылку на профиль', error_messages={'invalid': 'Пожалуйста, исправьте ошибку адресе профиля: похоже, он неправильный.'}, required=False ) vk = RegexField( regex=ur'^[a-zA-Z0-9-_]+$', widget=TextInput(attrs=dict(attrs_dict, maxlength=32)), max_length=32, label='Логин ВКонтакте', error_messages={'invalid': 'Пожалуйста, исправьте ошибку в логине VK: похоже, он неправильный'}, required=False ) class Meta: model = Author fields = ('bio', 'jabber', 'skype', 'tabun', 'forum', 'vk')
class RegistrationForm(Form): username = RegexField(label='Username', regex=r'^[\w.@+-]+$', max_length=30, error_messages=dict(invalid=MESSAGE_USERNAME)) email = EmailField(label='E-mail') password1 = CharField(widget=PasswordInput, label='Password') password2 = CharField(widget=PasswordInput, label='Password (again)') def clean_username(self): username = self.cleaned_data['username'] if len(username) < 3: raise ValidationError('Should be at least 3 letters') return username def clean_password1(self): password = self.cleaned_data['password1'] if len(set(password)) < 6: raise ValidationError(MESSAGE_PASS) for check in (string.digits, string.ascii_letters, SPECIAL_SYMBOLS): if len([i for i in password if i in check]) < 2: raise ValidationError(MESSAGE_PASS) return password def clean(self): if 'username' in self.cleaned_data and 'username' in self.cleaned_data: username = self.cleaned_data['username'] email = self.cleaned_data['email'] user = User.objects.filter(Q(username__iexact=username) | Q(email__iexact=email)) if user.exists(): raise ValidationError('Such username or email already exists.') if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise ValidationError('The two password fields didn\'t match.') return self.cleaned_data
class CustomUserChangeForm(ModelForm): username = RegexField( label=_('Username'), max_length=30, regex=r'^[\w.@+-]+$', help_text=_('Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.'), error_messages={ 'invalid': _('This value may contain only letters, numbers and ' '@/./+/-/_ characters.')}) password = ReadOnlyPasswordHashField(label=_('Password'), help_text=_('Raw passwords are not stored, so there is no way to see ' "this user's password, but you can change the password " 'using <a href=\'password/\'>this form</a>.')) class Meta: model = CustomUser fields = '__all__' def __init__(self, *args, **kwargs): super(CustomUserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial['password']
def test_change_regex_after_init(self): f = RegexField('^[a-z]+$') f.regex = '^[0-9]+$' self.assertEqual('1234', f.clean('1234')) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('abcd')
class NewUserForm(Form): """Form for getting a username and email for the creation of a new user. This form does not create the user by itself, but just gets the information necessary to create a new user account for a group. This form uses code from django's default UserCreationForm. """ error_messages = { 'duplicate_username': "******", } username = RegexField(label='Username', max_length=30, regex=r'^[\w.@+-]+$', error_messages = { 'invalid': "This value may contain only letters, numbers and " \ "@/./+/-/_ characters." } ) email = EmailField(label='Email') def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username'])
def test_regexfield_2(self): f = RegexField('^[0-9][A-F][0-9]$', required=False) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('3G3') self.assertEqual('', f.clean(''))
def test_change_regex_after_init(self): f = RegexField("^[a-z]+$") f.regex = "^[0-9]+$" self.assertEqual("1234", f.clean("1234")) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean("abcd")
class CreateDirectoryForm(Form): directory = ModelChoiceField(queryset=Directory.objects) name = RegexField( max_length=32, regex=r'^[\w]+$', error_messages={ 'invalid': _('This value may contain only letters, numbers and _ characters.') } ) def clean(self): cd = self.cleaned_data directory = cd.get('directory') name = cd.get('name') if directory and name: if Directory.objects.filter(parent=directory, name=name).count() != 0: raise ValidationError(_('Directory already exists')) def save(self): cd = self.cleaned_data d = Directory(parent=cd['directory'], owner=cd['directory'].owner, name=cd['name']) d.save() return d
class RegistrationForm(ModelForm): error_messages = { 'duplicate_username': _('A user with that username already exists.'), 'duplicate_email': _('A user with that email already exists.'), 'password_mismatch': _("The two password fields didn't match."), } username = RegexField( max_length=16, regex=r'^[\w.@+-]+$', error_messages={ 'invalid': _('This value may contain only letters, numbers and @/./+/-/_ characters.') } ) password1 = CharField(max_length=255) password2 = CharField(max_length=255) class Meta: model = CustomUser fields = ('username', 'email') def clean_username(self): username = self.cleaned_data['username'] try: CustomUser._default_manager.get(username__iexact=username) except CustomUser.DoesNotExist: return username raise ValidationError( self.error_messages['duplicate_username'], code='duplicate_username', ) def clean_email(self): email = self.cleaned_data['email'] try: CustomUser._default_manager.get(email=email) except CustomUser.DoesNotExist: return email raise ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user
class PotentialForm(ModelForm): """A form to create and modify records of potential members, based on the Potential model class.""" phone = RegexField(regex=r'^\d{3}-\d{3}-\d{4}$', min_length=12, max_length=12, required=True, help_text='XXX-XXX-XXXX') class Meta: """Associate the form with the Potential model.""" model = Potential
class InstanceRequestForm(ModelForm): fare_factory = RegexField(label="Fare model", max_length=200, regex=r'^[\w.]+') class Meta: model = InstanceRequest fields = ('comments', 'agency', 'fare_factory')
def test_regexfield_2(self): f = RegexField("^[0-9][A-F][0-9]$", required=False) self.assertEqual("2A2", f.clean("2A2")) self.assertEqual("3F3", f.clean("3F3")) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean("3G3") self.assertEqual("", f.clean(""))
class PledgeForm(ModelForm): """A form to create and modify records of pledges, based on the Potential model class with slight modifications.""" phone = RegexField(regex=r'^\d{3}-\d{3}-\d{4}$', min_length=12, max_length=12, required=True, help_text='XXX-XXX-XXXX') hidden = BooleanField(required=False, label='Initiated') class Meta: """Associate the form with the Potential model.""" model = Potential exclude = ('pledged',)
def test_regexfield_3(self): f = RegexField(re.compile('^[0-9][A-F][0-9]$')) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('3G3') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean(' 2A2') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('2A2 ')
class CustomUserCreationForm(ModelForm): ''' A form that creates a user, with no privileges, from the given username and password. ''' error_messages = { 'duplicate_username': _('A user with that username already exists.'), 'password_mismatch': _("The two password fields didn't match."), } username = RegexField(label=_('Username'), max_length=30, regex=r'^[\w.@+-]+$', help_text=_('Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.'), error_messages={ 'invalid': _('This value may contain only letters, numbers and ' '@/./+/-/_ characters.')}) password1 = CharField(label=_('Password'), widget=PasswordInput) password2 = CharField(label=_('Password confirmation'), widget=PasswordInput, help_text=_('Enter the same password as above, for verification.')) class Meta: model = CustomUser fields = ('username',) def clean_username(self): # Since CustomUser.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data['username'] try: CustomUser._default_manager.get(username__iexact=username) except CustomUser.DoesNotExist: return username raise ValidationError( self.error_messages['duplicate_username'], code='duplicate_username', ) def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user
class RecuperarSenha(ModelForm): cpf = RegexField(regex=r'^[0-9]+$', error_messages={ 'invalid_number': 'Por favor insira um CPF válido, somente números.' }) class Meta: model = cadastro_acesso fields = ['cpf']
def test_regexfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = RegexField(r'^[0-9]+$', min_length=5, max_length=10, error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID'], f.clean, 'abcde') self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234') self.assertFormErrors(['LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901')
def test_regexfield_3(self): f = RegexField(re.compile("^[0-9][A-F][0-9]$")) self.assertEqual("2A2", f.clean("2A2")) self.assertEqual("3F3", f.clean("3F3")) with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean("3G3") with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean(" 2A2") with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean("2A2 ")
def regex_field(self, field): max_length = None min_length = None for constraint in field.constraints: if isinstance(constraint, TextLengthConstraint): max_length = constraint.max min_length = constraint.min regex_field = RegexField("^[a-zA-Z0-9]+$", label=field.label, initial=field.value, required=field.is_required(), max_length=max_length, min_length=min_length, help_text=field.instruction, error_message=_("Only letters and numbers are valid"), ) regex_field.widget.attrs['class'] = css_class(field) return regex_field
def test_regexfield_4(self): f = RegexField('^[0-9]+$', min_length=5, max_length=10) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'"): f.clean('123') six.assertRaisesRegex( self, ValidationError, r"'Ensure this value has at least 5 characters \(it has 3\)\.'," r" u?'Enter a valid value\.'", f.clean, 'abc' ) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'"): f.clean('12345678901') with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean('12345a')
def test_regexfield(self): e = { "required": "REQUIRED", "invalid": "INVALID", "min_length": "LENGTH %(show_value)s, MIN LENGTH %(limit_value)s", "max_length": "LENGTH %(show_value)s, MAX LENGTH %(limit_value)s", } f = RegexField(r"^[0-9]+$", min_length=5, max_length=10, error_messages=e) self.assertFormErrors(["REQUIRED"], f.clean, "") self.assertFormErrors(["INVALID"], f.clean, "abcde") self.assertFormErrors(["LENGTH 4, MIN LENGTH 5"], f.clean, "1234") self.assertFormErrors(["LENGTH 11, MAX LENGTH 10"], f.clean, "12345678901")
class RegisterForm(Form): username = RegexField("^[0-9A-Za-z_]+$", label='username', min_length=6, max_length=100, required=True, error_messages={ 'invalid': 'username should only contain [0-9A-Za-z_]' }) email = EmailField(label='email') password = CharField(label='password', min_length=6, widget=PasswordInput(), required=True) password_again = CharField(label='confirm password', min_length=6, widget=PasswordInput(), required=True) def clean_username(self): username = self.cleaned_data.get('username') try: match = User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError(_('This username is already in use.')) def clean_email(self): email = self.cleaned_data.get('email') try: match = User.objects.get(email=email) except User.DoesNotExist: return email raise ValidationError(_('This email address is already in use.')) def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') password_again = cleaned_data.get('password_again') if password != password_again: raise ValidationError( _('password confirmation does not match password'))
class SaveFileForm(Form): directory = ModelChoiceField(queryset=Directory.objects) filename = RegexField( max_length=32, regex=r'^[\w]+$', error_messages={ 'invalid': _('This value may contain only letters, numbers and _ characters.') } ) content = CharField(required=False) def save(self): cd = self.cleaned_data f = File.objects.get_or_create(directory=cd['directory'], name=cd['filename'])[0] f.content = cd['content'] f.save() return f
class AllFieldTypesForm(Form): char = CharField() int_ = IntegerField() date = DateField() time = TimeField() datetime_ = DateTimeField() regex = RegexField(regex='^[a-f]{3}$') email = EmailField() file = FileField() # image = ImageField() url = URLField() bool = BooleanField() nullbool = NullBooleanField() choice = ChoiceField(choices=(('test choice', 'yay test choice'), )) multichoice = MultipleChoiceField(choices=( ('test choice', 'yay test choice'), ('test choice 2', 'yay another choice'), ('test choice 3', 'yay test choice'), )) float = FloatField() decimal = DecimalField() ip = IPAddressField() generic_ip = GenericIPAddressField() filepath = FilePathField(path=tempfile.gettempdir(), allow_files=True, allow_folders=True) slug = SlugField() typed_choice = TypedChoiceField(choices=( (1, 'test'), (2, 'test 2'), (3, 'bah'), ), coerce=int) typed_multichoice = TypedMultipleChoiceField(choices=( (1, 'test'), (2, 'test 2'), (3, 'bah'), ), coerce=int) model_choice = ModelChoiceField(queryset=get_user_model().objects.all()) model_multichoice = ModelMultipleChoiceField( queryset=get_user_model().objects.all())
class FileForm(Form): directory = ModelChoiceField(queryset=Directory.objects) filename = RegexField( max_length=32, regex=r'^[\w]+$', error_messages={ 'invalid': _('This value may contain only letters, numbers and _ characters.') } ) def clean(self): cd = self.cleaned_data directory = cd.get('directory') filename = cd.get('filename') if directory and filename: try: self.file_cache = File.objects.filter(directory=directory, name=filename).get() except File.DoesNotExist: raise ValidationError(_("File doesn't exist"))
class AuthorRegistrationForm(RegistrationFormUniqueEmail): attrs_dict = {'class': 'required input-xlarge'} username = RegexField( regex=ur'^[0-9a-zA-Z\u0430-\u044f\u0410-\u042f\u0451\u0401_@+-.. ]+$', widget=TextInput(attrs=dict(attrs_dict, maxlength=32)), max_length=32, label='Логин', help_text= 'Только русские/латинские буквы, цифры, пробел, точка и символы _ @ + -', error_messages={ 'invalid': 'Пожалуйста, исправьте ошибку в логине - он может содержать только русские/латинские буквы, цифры, пробел, точку и символы _ @ + -' }) email = EmailField( widget=TextInput(attrs=dict(attrs_dict, maxlength=75)), max_length=75, label='Электропочта', help_text='Адрес электронной почты для активации аккаунта', error_messages={ 'invalid': 'Пожалуйста, исправьте ошибку в адресе e-mail: похоже, он неправильный' }) password1 = CharField( widget=PasswordInput(attrs=attrs_dict, render_value=False), label="Пароль", help_text='Выбирайте сложный пароль', ) password2 = CharField( widget=PasswordInput(attrs=attrs_dict, render_value=False), label="Пароль (опять)", help_text='Повторите пароль, чтобы не забыть', ) recaptcha = ReCaptchaField( label="Капча", help_text='Введите два слова выше. Если трудно разобрать, обновите.', error_messages={ 'captcha_invalid': 'Это какая-то неправильная капча. Пожалуйста, введите снова.' })
def test_regexfield_4(self): f = RegexField("^[0-9]+$", min_length=5, max_length=10) with self.assertRaisesMessage( ValidationError, "'Ensure this value has at least 5 characters (it has 3).'"): f.clean("123") with self.assertRaisesMessage( ValidationError, "'Ensure this value has at least 5 characters (it has 3).', " "'Enter a valid value.'", ): f.clean("abc") self.assertEqual("12345", f.clean("12345")) self.assertEqual("1234567890", f.clean("1234567890")) with self.assertRaisesMessage( ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", ): f.clean("12345678901") with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): f.clean("12345a")