def __init__(self, *args,**kwargs): fields = ( CharField(show_hidden_initial=True), CharField(), ) if 'error_messages' not in kwargs or 'invalid' not in kwargs.get('error_messages'): if 'error_messages' not in kwargs: kwargs['error_messages'] = dict() kwargs['error_messages'].update(dict(invalid=_('Invalid CAPTCHA'))) widget_kwargs = dict( output_format = kwargs.get('output_format',None) or settings.CAPTCHA_OUTPUT_FORMAT ) for k in ('output_format',): if k in kwargs: del(kwargs[k]) super(CaptchaField,self).__init__(fields=fields, widget=CaptchaTextInput(**widget_kwargs), *args, **kwargs)
def __init__(self, *args, **kwargs): fields = ( CharField(show_hidden_initial=True), CharField(), ) if 'error_messages' not in kwargs or 'invalid' not in kwargs.get( 'error_messages'): if 'error_messages' not in kwargs: kwargs['error_messages'] = {} kwargs['error_messages'].update( {'invalid': ugettext_lazy('Invalid CAPTCHA')}) kwargs['widget'] = kwargs.pop( 'widget', CaptchaTextInput(output_format=kwargs.pop('output_format', None), id_prefix=kwargs.pop('id_prefix', None))) super(CaptchaField, self).__init__(fields, *args, **kwargs)
class EssayGradeForm(forms.Form): """ A form to validate essaygrade resources """ grader_type = ChoiceField(choices=GRADER_TYPES, required=True) feedback = CharField(min_length=0, required=False) annotated_text = CharField(min_length=0, required=False) success = BooleanField(required=True) confidence = DecimalField(required=False, max_value=1, max_digits=10) def __init__(self, problem_object = None, **kwargs): super(EssayGradeForm, self).__init__(**kwargs) self.max_target_scores = None if problem_object is not None: self.max_target_scores = problem_object.get('max_target_scores',None) validator = django_validators.JSONListValidator(matching_list=self.max_target_scores) self.fields['target_scores'] = fields.JSONListField(required = True, validators=[validator])
class ChannelForm(ModelForm): snippet = CharField(required=False, widget=Textarea()) class Meta: model = Channel fields = [ 'name', 'profile_image', 'description', 'snippet', 'background', 'public', 'hide' ]
def __init__(self, other_value=None, other_label=None, label='', **kwargs): self.choices = kwargs.pop('choices') if other_label: self.other_label = other_label if other_value: self.other_value = other_value # check that other_value provided is valid assert self.other_value.isidentifier(), wrong_value_msg self.choices = list(expand_choice_tuples(self.choices)) flat_choices = [i for i, j in self.choices] # check if value of choices start with other_val and divider, like 'other: SOMETHING' for i in flat_choices: assert not i.startswith(self.other_value), duplicate_err_msg self.choices += [(self.other_value, self.other_label), ] self.widget = OtherSelectorWidget(choices=self.choices, other_val=self.other_value) fields = (CharField(required=True), CharField(required=False),) super().__init__(fields=fields, require_all_fields=False, label=label, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['new_password1'] = CharField( max_length=64, min_length=8, label=self.password1_label, widget=PasswordInput(), error_messages={'required': REQUIRED_ERROR.format("password")}, )
class TextPluginForm(self.form): body = CharField(widget=widget, required=False) def __init__(self, *args, **kwargs): initial = kwargs.pop('initial', {}) if rendered_text: initial['body'] = rendered_text super(TextPluginForm, self).__init__(*args, initial=initial, **kwargs)
class SearchForm(forms.Form): search = CharField(required=False, min_length=3) search_in = ChoiceField(required=False, choices=CHOICES) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = "get" self.helper.add_input(Submit("", "Search"))
class ProcessNextStepForm(TextLinkFormMixin, ModelForm): link_content = CharField(required=False, label=_("Button Content"), widget=widgets.TextInput()) def __init__(self, raw_data=None, *args, **kwargs): instance = kwargs.get('instance') initial = instance and dict(instance.glossary) or {} initial.update(kwargs.pop('initial', {})) kwargs.update(initial=initial) super(ProcessNextStepForm, self).__init__(raw_data, *args, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['new_password1'] = CharField( max_length=64, label="Enter your new password", widget=PasswordInput(), error_messages={'required': REQUIRED_ERROR.format("password")}, ) self.fields['new_password2'].label = "Confirm new password" self.fields['old_password'].label = "Old password"
class SearchForm(forms.Form): name_field = CharField( widget=forms.TextInput( attrs={ 'class': 'autocomplete', # Materialize CSS class 'autocomplete': 'off' # Disable defeult browser autocomplete }), label="Rechercher une substance", label_suffix='')
class SecurityForm(ModelForm): password1 = CharField(widget=PasswordInput(), required=False) password2 = CharField(widget=PasswordInput(), required=False) def clean_password2(self): instance = getattr(self, 'instance', None) assert isinstance(instance, User) password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 != password2: raise ValidationError(_("Passwords doesn't match")) else: return password2 class Meta: model = User exclude = ('api_key', 'username', 'password')
def test_callable_default(): def default(): return ["1", "2"] field = DynamicArrayField(CharField(max_length=10), required=True, default=default) data = [] cleaned_data = field.clean(data) assert cleaned_data == default()
class CustomSetPasswordForm(SetPasswordForm): new_password1 = CharField(label=_('Nouveau mot de passe'), widget=PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Nouveau mot de passe', 'autocomplete': 'off' }), strip=False) new_password2 = CharField( label=_('Nouveau mot de passe confirmation'), widget=PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Nouveau mot de passe confirmation', 'autocomplete': 'off' }), strip=False, )
class LoginForm(AuthenticationForm): username = CharField( max_length=30, label='Username', error_messages={'required': REQUIRED_ERROR.format("username")}, ) password = CharField( max_length=64, label="Password", widget=PasswordInput(), error_messages={'required': REQUIRED_ERROR.format("password")}, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if TenantApi.site_settings( 'DISABLE_SIGNUP', cast=bool, request=self.request, ): label = 'Email Address' else: label = 'Username' self.fields['username'] = CharField( max_length=64, label=label, error_messages={'required': REQUIRED_ERROR.format(label)}, ) def confirm_login_allowed(self, user): super().confirm_login_allowed(user) current_site_id = self.request.site.id if user.account.site_id is not current_site_id: error_msg = 'user site_id not matching in login request' if settings.DEBUG: logger.error(error_msg) else: logger.warn(error_msg) raise ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, )
def __init__(self, num_lines=3, *args, **kwargs): fields = tuple([ CharField(widget=TextInput(attrs={'class': 'input-xxlarge'})) for _ in range(0, num_lines) ]) self.widget = BootstrapAddressFieldWidget( widgets=[field.widget for field in fields]) super(BootstrapAddressField, self).__init__(fields=fields, *args, **kwargs)
class HairintaForm(ContactsForm): class Media: js = ('js/conditional_fields.js', ) msg = CharField(label='Kerro omin sanoin tapahtuneesta.', widget=Textarea) msg1 = CharField(label='Oliko paikalla muita henkilöitä?', widget=Textarea) res = BooleanField(label='Haluan, että minulle vastataan.', widget=CheckboxInput(attrs=dict( onclick='contactMe("res", ["name", "email"])')), required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields.get('email').widget = TextInput(attrs=dict( style='display: none')) self.fields.get('name').widget = TextInput(attrs=dict( style='display: none'))
def finalize_recipient_field(name, model): if FieldsConfig.get_4_model(model).is_fieldname_hidden('email'): self.fields[name] = CharField( label=self.fields[name].label, required=False, widget=Label, initial=gettext( 'Beware: the field «Email address» is hidden ;' ' please contact your administrator.'), )
class RevisionDashboardForm(forms.Form): ALL_AUTHORS = 0 KNOWN_AUTHORS = 1 UNKNOWN_AUTHORS = 2 AUTHOR_CHOICES = [ (ALL_AUTHORS, _("All Authors")), (KNOWN_AUTHORS, _("Known Authors")), (UNKNOWN_AUTHORS, _("Unknown Authors")), ] locale = forms.ChoiceField( choices=LANG_CHOICES, # Required for non-translations, which is # enforced in Document.clean(). required=False, label=_("Locale:"), ) user = CharField(min_length=1, max_length=255, required=False, label=_("User:"******"Topic:")) start_date = forms.DateField( required=False, label=_("Start Date:"), input_formats=["%m/%d/%Y"], widget=forms.TextInput(attrs={"pattern": r"\d{1,2}/\d{1,2}/\d{4}"}), ) end_date = forms.DateField( required=False, label=_("End Date:"), input_formats=["%m/%d/%Y"], widget=forms.TextInput(attrs={"pattern": r"\d{1,2}/\d{1,2}/\d{4}"}), ) preceding_period = forms.ChoiceField(choices=PERIOD_CHOICES, required=False, label=_("Preceding Period:")) authors = forms.ChoiceField(choices=AUTHOR_CHOICES, required=False, label=_("Authors"))
def __init__(self, items, *args, **kwargs): super(PaymentHiddenInputsPostForm, self).__init__(*args, **kwargs) for key in items: if type(items[key]) in [list, tuple]: self.fields[key] = MultipleChoiceField( initial=items[key], widget=widgets.MultipleHiddenInput) else: self.fields[key] = CharField(initial=items[key], widget=HiddenInput)
def __init__(self, *args, **kwargs): fields = (CharField(show_hidden_initial=True), CharField()) if "error_messages" not in kwargs or "invalid" not in kwargs.get( "error_messages"): if "error_messages" not in kwargs: kwargs["error_messages"] = {} kwargs["error_messages"].update( {"invalid": ugettext_lazy("Invalid CAPTCHA")}) kwargs["widget"] = kwargs.pop( "widget", CaptchaTextInput( output_format=kwargs.pop("output_format", None), id_prefix=kwargs.pop("id_prefix", None), generator=kwargs.pop("generator", None), ), ) super(CaptchaField, self).__init__(fields, *args, **kwargs)
class LyricForm(ModelForm): lines = SimpleArrayField(CharField(), delimiter='|', widget=Textarea()) def __init__(self, *args, **kwargs): super(LyricForm, self).__init__(*args, **kwargs) if self.instance.lines: self.instance.lines = '\r\n'.join(self.instance.lines) super(LyricForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): max_length = kwargs.pop('max_length', None) del max_length fields = ( VersatileImageFormField(label='Image'), CharField(required=False) ) super(VersatileImagePPOIClickField, self).__init__( tuple(fields), *args, **kwargs )
class PendingMailForm(Form): code = CharField(required=True) email = CharField(required=True) def clean(self): cleaned_data = super(PendingMailForm, self).clean() if cleaned_data.get('code', None): try: self.instance = PendingMailVerifyer.objects.get( code=cleaned_data['code']) except PendingMailVerifyer.DoesNotExist: raise ValidationError( 'Gegevens van email validatie komen niet overeen.', code='invalid', params={}, ) if self.instance.email != cleaned_data['email']: raise ValidationError( 'Gegevens van email validatie komen niet overeen.', code='invalid', params={}, ) if self.instance.is_verified: raise ValidationError( 'Mail is al gevalideerd', code='already_validated', params={}, ) if not self.instance.active: raise ValidationError( 'Deze email verificatie link is niet meer actief. Mogelijk dat de gebruiker het e-mail adres heeft ' 'aangepast.', code='not_active', params={}, ) def verify(self): self.instance.verify()
class ImageFormMixin(EntangledModelFormMixin): image_file = CascadeImageField() image_title = CharField( label=_('Image Title'), required=False, help_text=_( "Caption text added to the 'title' attribute of the <img> element." ), ) alt_tag = CharField( label=_('Alternative Description'), required=False, help_text= _("Textual description of the image added to the 'alt' tag of the <img> element." ), ) _image_properties = EntangledField() class Meta: entangled_fields = { 'glossary': ['image_file', 'image_title', 'alt_tag', '_image_properties'] } def __init__(self, *args, **kwargs): if not getattr(self, 'require_image', True): self.base_fields['image_file'].required = False super().__init__(*args, **kwargs) def clean_image_file(self): image_file = self.cleaned_data['image_file'] # _image_properties are just a cached representation, maybe useless if image_file: self.cleaned_data['_image_properties'] = { 'width': image_file._width, 'height': image_file._height, 'exif_orientation': image_file.exif.get('Orientation', 1), } return image_file
def get_form(self, request, obj=None, **kwargs): link_content = CharField(required=False, label=_("Button Content"), widget=widgets.TextInput()) Form = type(str('ButtonForm'), ( TextLinkFormMixin, getattr(LinkForm, 'get_form_class')(), ), {'link_content': link_content}) kwargs.update(form=Form) return super(BootstrapButtonPlugin, self).get_form(request, obj, **kwargs)
def __init__(self, lookup_class, *args, **kwargs): self.widget = ComplexFieldWidget(lookup_class=lookup_class, attrs={'title': self.help_text}) fields = [] fields.append( AutoCompleteSelectField( lookup_class=lookup_class, required=False, )) fields.append(CharField()) super(ComplexField, self).__init__(fields, *args, **kwargs)
class ReviewForm(ModelForm): choices = [('1', 'Very poor'), ('2', 'Poor'), ('3', 'Not bad'), ('4', 'Good'), ('5', 'Very Good')] rating = ChoiceField( choices=choices, widget=forms.RadioSelect(renderer=HorizontalRadioRenderer)) opinion = CharField(widget=forms.Textarea) class Meta: fields = ['rating', 'opinion'] model = Review
class ArticleAdminModelForm(ModelForm): body = CharField(widget=MarkdownWidget()) headline = CharField(label='Título', widget=TextInput(attrs={'style': 'width:600px'})) tags = TagField(widget=TagAutocompleteTagIt(max_tags=False), required=False) def clean_tags(self): """ This is a hack to bypass the bug that: 1 tag with spaces is considered as many tags by the lib. This doesn't ocurr with 2 tags or more. With double quotes, the tag with spaces is correctly interpreted. """ tags = self.cleaned_data.get('tags') if tags and ',' not in tags: # there is just 1 tag tags = tags.strip('"') tags = '"' + tags + '"' return tags class Meta: model = Article
def __init__(self, *args, model_instance=None, **kwargs): result = super().__init__(*args, **kwargs) self.fields['description'] = CharField( initial=model_instance and model_instance.description or None, label=_('New Description'), widget=DescriptionTask( instance_pk=model_instance and model_instance.pk or None)) return result
def __init__(self, lookup_name, *args, **kwargs): kwargs.pop('widget', 1) #dummy True value, to remove widget argument CharField.__init__(self, widget=AutocompleteTextInput(lookup_name, kwargs.pop('widget_attrs', {})), *args, **kwargs) #setting current widget as an autocomplete text input AutocompleteField.__init__(self, lookup_name)
def test_label_with_help(self): field = CharField(label='Foo', help_text='Foo bar') field.auto_id = 'foo' expect = '<label for="foo" title="Foo bar">Foo</label>' eq_(expect, label_with_help(field))