Python django.forms.CharField() Examples

The following are code examples for showing how to use django.forms.CharField(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-places   Author: oscarmcm   File: forms.py    MIT License 10 votes vote down vote up
def __init__(self, *args, **kwargs):
        fields = (
            forms.CharField(label=_('place')),
            forms.DecimalField(label=_('Latitude')),
            forms.DecimalField(label=_('Longitude')),
        )
        if 'initial' in kwargs:
            kwargs['initial'] = Places(*kwargs['initial'].split(','))
        self.widget = PlacesWidget()
        super(PlacesField, self).__init__(fields, **kwargs) 
Example 2
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_title_field(self):
        """
        The model should have a title field
        """
        field = OmniFormBase._meta.get_field('title')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 3
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_form_class(self):
        """
        The _get_form_class method should return a form class
        """
        form_class = self.omniform.get_form_class()
        self.assertTrue(issubclass(form_class, OmniFormBaseForm))
        self.assertEqual(form_class.__name__, 'OmniFormTestModel')
        form = form_class()

        # Test the title field
        self.assertIsInstance(form.fields['title'], forms.CharField)
        self.assertIsInstance(form.fields['title'].widget, forms.TextInput)
        self.assertEqual(form.fields['title'].label, 'Please give us a title')
        self.assertEqual(form.fields['title'].initial, 'Some title...')
        self.assertTrue(form.fields['title'].required)

        # Test the agree field
        self.assertIsInstance(form.fields['agree'], forms.BooleanField)
        self.assertIsInstance(form.fields['agree'].widget, forms.CheckboxInput)
        self.assertEqual(form.fields['agree'].label, 'Please agree')
        self.assertTrue(form.fields['agree'].initial)
        self.assertTrue(form.fields['agree'].required) 
Example 4
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_fields(self):
        """
        The method should return the correct fields as a dict
        """
        fields = self.omniform._get_fields()
        self.assertEqual(2, len(fields))

        # Test the title field
        self.assertIsInstance(fields['title'], forms.CharField)
        self.assertIsInstance(fields['title'].widget, forms.TextInput)
        self.assertEqual(fields['title'].label, 'Please give us a title')
        self.assertEqual(fields['title'].initial, 'Some title...')
        self.assertTrue(fields['title'].required)

        # Test the agree field
        self.assertIsInstance(fields['agree'], forms.BooleanField)
        self.assertIsInstance(fields['agree'].widget, forms.CheckboxInput)
        self.assertEqual(fields['agree'].label, 'Please agree')
        self.assertTrue(fields['agree'].initial)
        self.assertTrue(fields['agree'].required) 
Example 5
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_field(self):
        """
        The _get_field method should return a form field instance
        """
        field_1 = self.omniform._get_field('title')
        field_2 = self.omniform._get_field('agree')
        field_3 = self.omniform._get_field('fictional')
        self.assertIsInstance(field_1, forms.CharField)
        self.assertIsInstance(field_1.widget, forms.TextInput)
        self.assertEqual(field_1.label, 'Please give us a title')
        self.assertTrue(field_1.required)
        self.assertIsInstance(field_2, forms.BooleanField)
        self.assertIsInstance(field_2.widget, forms.CheckboxInput)
        self.assertEqual(field_2.label, 'Please agree')
        self.assertTrue(field_2.required)
        self.assertIsNone(field_3) 
Example 6
Project: Servo   Author: fpsw   File: repairs.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        components = kwargs.get('components')
        del(kwargs['components'])
        super(GsxComponentForm, self).__init__(*args, **kwargs)

        if len(components):
            components = json.loads(components)
            for k, v in components.items():
                self.fields[k] = forms.CharField(label=k, required=True, initial=v) 
Example 7
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_name_field(self):
        """
        The model should have a name field
        """
        field = OmniField._meta.get_field('name')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 8
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_widget_class_field(self):
        """
        The model should have a widget_class field
        """
        field = OmniField._meta.get_field('widget_class')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 9
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_get_concrete_class_for_model_field(self):
        """
        The get_concrete_class_for_model_field method should return the correct OmniField subclass
        """
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.CharField()), OmniCharField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.NullBooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DateTimeField()), OmniDateTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DecimalField()), OmniDecimalField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.EmailField()), OmniEmailField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FloatField()), OmniFloatField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.IntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BigIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.PositiveIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SmallIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.TimeField()), OmniTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.URLField()), OmniUrlField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SlugField()), OmniSlugField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FileField()), OmniFileField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.ImageField()), OmniImageField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DurationField()), OmniDurationField)
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.GenericIPAddressField()),
            OmniGenericIPAddressField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.CommaSeparatedIntegerField()),
            OmniCharField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.PositiveSmallIntegerField()),
            OmniIntegerField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ForeignKey(DummyModel2)),
            OmniForeignKeyField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ManyToManyField(DummyModel2)),
            OmniManyToManyField
        ) 
Example 10
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_field_class(self):
        """
        The model should define the correct field class
        """
        self.assertEqual(OmniCharField.FIELD_CLASS, 'django.forms.CharField') 
Example 11
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_protocol(self):
        """
        The model should have a protocol field
        """
        field = OmniGenericIPAddressField._meta.get_field('protocol')
        self.assertIsInstance(field, models.CharField)
        self.assertTrue(field.blank)
        self.assertFalse(field.null)
        self.assertEqual(field.max_length, 4)
        self.assertEqual(field.choices, OmniGenericIPAddressField.PROTOCOL_CHOICES)
        self.assertEqual(field.default, OmniGenericIPAddressField.PROTOCOL_BOTH) 
Example 12
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_name_field(self):
        """
        The model should have a name field
        """
        field = OmniFormHandler._meta.get_field('name')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 13
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_subject_field(self):
        """
        The model should have a subject field
        """
        field = OmniFormEmailConfirmationHandler._meta.get_field('subject')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 14
Project: openhatch   Author: campbe13   File: admin.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def periodic_task_form():
    loaders.autodiscover()
    tasks = list(sorted(registry.tasks.regular().keys()))
    choices = (("", ""), ) + tuple(zip(tasks, tasks))

    class PeriodicTaskForm(forms.ModelForm):
        regtask = LaxChoiceField(label=_(u"Task (registered)"),
                                 choices=choices, required=False)
        task = forms.CharField(label=_("Task (custom)"), required=False,
                               max_length=200)

        class Meta:
            model = PeriodicTask

        def clean(self):
            data = super(PeriodicTaskForm, self).clean()
            regtask = data.get("regtask")
            if regtask:
                data["task"] = regtask
            if not data["task"]:
                exc = forms.ValidationError(_(u"Need name of task"))
                self._errors["task"] = self.error_class(exc.messages)
                raise exc
            return data

    return PeriodicTaskForm 
Example 15
Project: wagtailcloudinary   Author: dteskera   File: blocks.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def field(self):
        from .fields import CloudinaryWidget
        field_kwargs = {'widget': CloudinaryWidget()}
        field_kwargs.update(self.field_options)
        return forms.CharField(**field_kwargs)
    #
    # def get_searchable_content(self, value):
    #     return [force_text(value)] 
Example 16
Project: django-glitter   Author: developersociety   File: fields.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_python(self, value):
        # Slightly evil - ignore URLField's to_python if we're starting with mailto:
        value = super(CharFormField, self).to_python(value)

        if value and value.lower().startswith('mailto:'):
            return value

        # Go through URLField's to_python
        value = super().to_python(value)

        return value 
Example 17
Project: pretix-espass   Author: esPass   File: signals.py    Apache License 2.0 5 votes vote down vote up
def register_global_settings(sender, **kwargs):
    return OrderedDict([

        ('esPass_organizer_name', forms.CharField(
            label='esPass organizer name',
            required=False,
        ))
    ]) 
Example 18
Project: pretix-espass   Author: esPass   File: espass.py    Apache License 2.0 5 votes vote down vote up
def settings_form_fields(self) -> dict:
        return OrderedDict(
            list(super().settings_form_fields.items()) + [
                ('icon',
                 PNGImageField(
                     label=_('Event icon'),
                     help_text=_('We suggest an upload size of 96x96 pixels - the display size is 48dp'),
                     required=True,
                 )),
                ('logo',
                 PNGImageField(
                     label=_('Event logo'),
                     help_text=_('Upload a nice big image - size depends on the device - example size 800x600'),
                     required=True,
                 )),
                ('location_name',
                 forms.CharField(
                     label=_('Event location name'),
                     required=False
                 )),
                ('latitude',
                 forms.FloatField(
                     label=_('Event location latitude'),
                     required=False
                 )),
                ('longitude',
                 forms.FloatField(
                     label=_('Event location longitude'),
                     required=False
                 )),
            ]
        ) 
Example 19
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """
        Returns a django.forms.Field instance for this database Field.
        """
        defaults = {'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text}
        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default
                defaults['show_hidden_initial'] = True
            else:
                defaults['initial'] = self.get_default()
        if self.choices:
            # Fields with choices get special treatment.
            include_blank = (self.blank or
                             not (self.has_default() or 'initial' in kwargs))
            defaults['choices'] = self.get_choices(include_blank=include_blank)
            defaults['coerce'] = self.to_python
            if self.null:
                defaults['empty_value'] = None
            if choices_form_class is not None:
                form_class = choices_form_class
            else:
                form_class = forms.TypedChoiceField
            # Many of the subclass-specific formfield arguments (min_value,
            # max_value) don't apply for choice fields, so be sure to only pass
            # the values that TypedChoiceField will understand.
            for k in list(kwargs):
                if k not in ('coerce', 'empty_value', 'choices', 'required',
                             'widget', 'label', 'initial', 'help_text',
                             'error_messages', 'show_hidden_initial'):
                    del kwargs[k]
        defaults.update(kwargs)
        if form_class is None:
            form_class = forms.CharField
        return form_class(**defaults) 
Example 20
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example 21
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(CharField, self).check(**kwargs)
        errors.extend(self._check_max_length_attribute(**kwargs))
        return errors 
Example 22
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example 23
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(CharField, self).get_prep_value(value)
        return self.to_python(value) 
Example 24
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause email validation to be performed
        # twice.
        defaults = {
            'form_class': forms.EmailField,
        }
        defaults.update(kwargs)
        return super(EmailField, self).formfield(**defaults) 
Example 25
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length, 'widget': forms.Textarea}
        defaults.update(kwargs)
        return super(TextField, self).formfield(**defaults) 
Example 26
Project: chattR   Author: patrickstocklin   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause URL validation to be performed
        # twice.
        defaults = {
            'form_class': forms.URLField,
        }
        defaults.update(kwargs)
        return super(URLField, self).formfield(**defaults) 
Example 27
Project: django-boost   Author: ChanTsune   File: tests.py    MIT License 5 votes vote down vote up
def test_field(self):
        from django import forms
        from django_boost.forms.mixins import FieldRenameMixin

        class MyForm(FieldRenameMixin, forms.Form):
            token_id = forms.CharField()
            rename_fields = {"token_id": "token-id"}

        form = MyForm()

        self.assertIn("token-id", form.fields.keys())
        self.assertNotIn("token_id", form.fields.keys()) 
Example 28
Project: django-fuzzers   Author: guidovranken   File: utils.py    MIT License 5 votes vote down vote up
def test_forms_CharField(inp):
    try:
        forms.CharField().clean(inp)
    except:
        pass 
Example 29
Project: django-oscar-ficta   Author: okfish   File: forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        for_user = None
        default_person = None
        choices = None
        label = _("Juristic persons list")
        help_text = _("Select a company from the list or <a href='/shop/accounts/person/register/' data-toggle='tooltip' title='Create a new juristic person'>add a new</a>")
        if 'for_user' in kwargs.keys():
            for_user = kwargs.pop('for_user')
            widget = forms.HiddenInput
            choices = get_persons_choices(for_user)
            if not choices is None and len(choices) > 0:
                widget=RadioSelect
            else:
                label = _("No juristic persons found")
                
        else:
            # if no user given renders Select2 widget 
            # full list of persons will be used
            widget = PersonRemoteSelect
            label = _("All available persons")
            help_text = _("active juristic persons")
            
        if 'default_person' in kwargs.keys():
            default_person = kwargs.pop('default_person')
            
        super(PersonSelectForm, self).__init__(*args, **kwargs)
        
        if for_user:
            self.fields['person'] = forms.ChoiceField(label=label,
                                                      initial=default_person,
                                                      required=False,
                                                      choices=choices,
                                                      widget=widget,
                                                      help_text=help_text)
        else:
            
            self.fields['person'] = forms.CharField(label=label,
                                                    widget=widget,
                                                    help_text=help_text) 
Example 30
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """
        Returns a django.forms.Field instance for this database Field.
        """
        defaults = {'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text}
        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default
                defaults['show_hidden_initial'] = True
            else:
                defaults['initial'] = self.get_default()
        if self.choices:
            # Fields with choices get special treatment.
            include_blank = (self.blank or
                             not (self.has_default() or 'initial' in kwargs))
            defaults['choices'] = self.get_choices(include_blank=include_blank)
            defaults['coerce'] = self.to_python
            if self.null:
                defaults['empty_value'] = None
            if choices_form_class is not None:
                form_class = choices_form_class
            else:
                form_class = forms.TypedChoiceField
            # Many of the subclass-specific formfield arguments (min_value,
            # max_value) don't apply for choice fields, so be sure to only pass
            # the values that TypedChoiceField will understand.
            for k in list(kwargs):
                if k not in ('coerce', 'empty_value', 'choices', 'required',
                             'widget', 'label', 'initial', 'help_text',
                             'error_messages', 'show_hidden_initial'):
                    del kwargs[k]
        defaults.update(kwargs)
        if form_class is None:
            form_class = forms.CharField
        return form_class(**defaults) 
Example 31
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example 32
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example 33
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length}
        defaults.update(kwargs)
        return super(CharField, self).formfield(**defaults)

# TODO: Maybe move this into contrib, because it's specialized. 
Example 34
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        # max_length should be overridden to 254 characters to be fully
        # compliant with RFCs 3696 and 5321

        kwargs['max_length'] = kwargs.get('max_length', 75)
        CharField.__init__(self, *args, **kwargs) 
Example 35
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, verbose_name=None, name=None, **kwargs):
        kwargs['max_length'] = kwargs.get('max_length', 200)
        CharField.__init__(self, verbose_name, name, **kwargs) 
Example 36
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause URL validation to be performed
        # twice.
        defaults = {
            'form_class': forms.URLField,
        }
        defaults.update(kwargs)
        return super(URLField, self).formfield(**defaults) 
Example 37
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """
        Returns a django.forms.Field instance for this database Field.
        """
        defaults = {'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text}
        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default
                defaults['show_hidden_initial'] = True
            else:
                defaults['initial'] = self.get_default()
        if self.choices:
            # Fields with choices get special treatment.
            include_blank = (self.blank or
                             not (self.has_default() or 'initial' in kwargs))
            defaults['choices'] = self.get_choices(include_blank=include_blank)
            defaults['coerce'] = self.to_python
            if self.null:
                defaults['empty_value'] = None
            if choices_form_class is not None:
                form_class = choices_form_class
            else:
                form_class = forms.TypedChoiceField
            # Many of the subclass-specific formfield arguments (min_value,
            # max_value) don't apply for choice fields, so be sure to only pass
            # the values that TypedChoiceField will understand.
            for k in list(kwargs):
                if k not in ('coerce', 'empty_value', 'choices', 'required',
                             'widget', 'label', 'initial', 'help_text',
                             'error_messages', 'show_hidden_initial'):
                    del kwargs[k]
        defaults.update(kwargs)
        if form_class is None:
            form_class = forms.CharField
        return form_class(**defaults) 
Example 38
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example 39
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(CharField, self).check(**kwargs)
        errors.extend(self._check_max_length_attribute(**kwargs))
        return errors 
Example 40
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example 41
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(CharField, self).get_prep_value(value)
        return self.to_python(value) 
Example 42
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause email validation to be performed
        # twice.
        defaults = {
            'form_class': forms.EmailField,
        }
        defaults.update(kwargs)
        return super(EmailField, self).formfield(**defaults) 
Example 43
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length, 'widget': forms.Textarea}
        defaults.update(kwargs)
        return super(TextField, self).formfield(**defaults) 
Example 44
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause URL validation to be performed
        # twice.
        defaults = {
            'form_class': forms.URLField,
        }
        defaults.update(kwargs)
        return super(URLField, self).formfield(**defaults) 
Example 45
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """
        Returns a django.forms.Field instance for this database Field.
        """
        defaults = {'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text}
        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default
                defaults['show_hidden_initial'] = True
            else:
                defaults['initial'] = self.get_default()
        if self.choices:
            # Fields with choices get special treatment.
            include_blank = (self.blank or
                             not (self.has_default() or 'initial' in kwargs))
            defaults['choices'] = self.get_choices(include_blank=include_blank)
            defaults['coerce'] = self.to_python
            if self.null:
                defaults['empty_value'] = None
            if choices_form_class is not None:
                form_class = choices_form_class
            else:
                form_class = forms.TypedChoiceField
            # Many of the subclass-specific formfield arguments (min_value,
            # max_value) don't apply for choice fields, so be sure to only pass
            # the values that TypedChoiceField will understand.
            for k in list(kwargs):
                if k not in ('coerce', 'empty_value', 'choices', 'required',
                             'widget', 'label', 'initial', 'help_text',
                             'error_messages', 'show_hidden_initial'):
                    del kwargs[k]
        defaults.update(kwargs)
        if form_class is None:
            form_class = forms.CharField
        return form_class(**defaults) 
Example 46
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example 47
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(CharField, self).check(**kwargs)
        errors.extend(self._check_max_length_attribute(**kwargs))
        return errors 
Example 48
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example 49
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(CharField, self).get_prep_value(value)
        return self.to_python(value) 
Example 50
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause email validation to be performed
        # twice.
        defaults = {
            'form_class': forms.EmailField,
        }
        defaults.update(kwargs)
        return super(EmailField, self).formfield(**defaults) 
Example 51
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length, 'widget': forms.Textarea}
        defaults.update(kwargs)
        return super(TextField, self).formfield(**defaults) 
Example 52
Project: GTDWeb   Author: lanbing510   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause URL validation to be performed
        # twice.
        defaults = {
            'form_class': forms.URLField,
        }
        defaults.update(kwargs)
        return super(URLField, self).formfield(**defaults) 
Example 53
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_checks(self):
        class BadField(models.Model):
            field = encrypt(models.CharField())

            class Meta:
                app_label = 'myapp'

        model = BadField()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        # The inner CharField is missing a max_length.
        self.assertEqual('fields.E120', errors[0].id)
        self.assertIn('max_length', errors[0].msg) 
Example 54
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_deconstruct_args(self):
        field = encrypt(models.CharField(max_length=20))
        name, path, args, kwargs = field.deconstruct()
        new = encrypt(*args, **kwargs)
        self.assertEqual(new.max_length, field.max_length) 
Example 55
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_model_field_formfield(self):
        model_field = encrypt(models.CharField(max_length=27))
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, forms.CharField)
        self.assertEqual(form_field.max_length, 27) 
Example 56
Project: cmsplugin-form-handler   Author: mkoistinen   File: forms.py    MIT License 5 votes vote down vote up
def __init__(self, source_url, instance, **kwargs):
        """
        Extracts what we need from the modified signature, then instantiates
        the form as usual.
        """
        super(FormPluginFormMixin, self).__init__(**kwargs)
        self.fields['cmsplugin_form_source_url'] = forms.CharField(
            widget=forms.HiddenInput, initial=source_url)
        self.plugin_id = instance.pk 
Example 57
Project: django-hashid-field   Author: nshafer   File: field.py    MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'form_class': forms.CharField}
        defaults.update(kwargs)
        if defaults.get('widget') == admin_widgets.AdminIntegerFieldWidget:
            defaults['widget'] = admin_widgets.AdminTextInputWidget
        return super().formfield(**defaults) 
Example 58
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """
        Returns a django.forms.Field instance for this database Field.
        """
        defaults = {'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text}
        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default
                defaults['show_hidden_initial'] = True
            else:
                defaults['initial'] = self.get_default()
        if self.choices:
            # Fields with choices get special treatment.
            include_blank = (self.blank or
                             not (self.has_default() or 'initial' in kwargs))
            defaults['choices'] = self.get_choices(include_blank=include_blank)
            defaults['coerce'] = self.to_python
            if self.null:
                defaults['empty_value'] = None
            if choices_form_class is not None:
                form_class = choices_form_class
            else:
                form_class = forms.TypedChoiceField
            # Many of the subclass-specific formfield arguments (min_value,
            # max_value) don't apply for choice fields, so be sure to only pass
            # the values that TypedChoiceField will understand.
            for k in list(kwargs):
                if k not in ('coerce', 'empty_value', 'choices', 'required',
                             'widget', 'label', 'initial', 'help_text',
                             'error_messages', 'show_hidden_initial', 'disabled'):
                    del kwargs[k]
        defaults.update(kwargs)
        if form_class is None:
            form_class = forms.CharField
        return form_class(**defaults) 
Example 59
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example 60
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(CharField, self).check(**kwargs)
        errors.extend(self._check_max_length_attribute(**kwargs))
        return errors 
Example 61
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example 62
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(CharField, self).get_prep_value(value)
        return self.to_python(value) 
Example 63
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause email validation to be performed
        # twice.
        defaults = {
            'form_class': forms.EmailField,
        }
        defaults.update(kwargs)
        return super(EmailField, self).formfield(**defaults) 
Example 64
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length, 'widget': forms.Textarea}
        defaults.update(kwargs)
        return super(TextField, self).formfield(**defaults) 
Example 65
Project: liberator   Author: libscie   File: __init__.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause URL validation to be performed
        # twice.
        defaults = {
            'form_class': forms.URLField,
        }
        defaults.update(kwargs)
        return super(URLField, self).formfield(**defaults) 
Example 66
Project: otreeutils   Author: WZBSocialScienceCenter   File: pages.py    Apache License 2.0 5 votes vote down vote up
def vars_for_template(self):
        """Sets variables for template: Question form and additional data"""
        # create question form
        form = _UnderstandingQuestionsForm()

        # add questions to form
        questions = self.get_questions()
        for q_idx, q_def in enumerate(questions):
            answer_field = forms.ChoiceField(label=q_def['question'],
                                             choices=_choices_for_field(q_def['options']))
            correct_val_field = forms.CharField(initial=q_def['correct'],
                                                widget=forms.HiddenInput)
            hint_field = forms.CharField(initial=q_def.get('hint', self.default_hint),
                                         widget=forms.HiddenInput)
            form.add_field('q_input_%d' % q_idx, answer_field)
            form.add_field('q_correct_%d' % q_idx, correct_val_field)
            form.add_field('q_hint_%d' % q_idx, hint_field)

        # optionally add field with number of wrong attempts
        if self.form_model and self.form_field_n_wrong_attempts:
            form.add_field(self.form_field_n_wrong_attempts, forms.CharField(initial=0, widget=forms.HiddenInput))

        return {
            'questions_form': form,
            'n_questions': len(questions),
            'hint_empty': self.default_hint_empty,
            'form_field_n_wrong_attempts': self.form_field_n_wrong_attempts or '',
            'set_correct_answers': str(self.set_correct_answers and self.debug).lower(),
        } 
Example 67
Project: banruo   Author: yingshang   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """Return a django.forms.Field instance for this field."""
        defaults = {'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text}
        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default
                defaults['show_hidden_initial'] = True
            else:
                defaults['initial'] = self.get_default()
        if self.choices:
            # Fields with choices get special treatment.
            include_blank = (self.blank or
                             not (self.has_default() or 'initial' in kwargs))
            defaults['choices'] = self.get_choices(include_blank=include_blank)
            defaults['coerce'] = self.to_python
            if self.null:
                defaults['empty_value'] = None
            if choices_form_class is not None:
                form_class = choices_form_class
            else:
                form_class = forms.TypedChoiceField
            # Many of the subclass-specific formfield arguments (min_value,
            # max_value) don't apply for choice fields, so be sure to only pass
            # the values that TypedChoiceField will understand.
            for k in list(kwargs):
                if k not in ('coerce', 'empty_value', 'choices', 'required',
                             'widget', 'label', 'initial', 'help_text',
                             'error_messages', 'show_hidden_initial', 'disabled'):
                    del kwargs[k]
        defaults.update(kwargs)
        if form_class is None:
            form_class = forms.CharField
        return form_class(**defaults) 
Example 68
Project: banruo   Author: yingshang   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example 69
Project: banruo   Author: yingshang   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length}
        # TODO: Handle multiple backends with different feature flags.
        if self.null and not connection.features.interprets_empty_strings_as_nulls:
            defaults['empty_value'] = None
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example 70
Project: banruo   Author: yingshang   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # As with CharField, this will cause email validation to be performed
        # twice.
        return super().formfield(**{
            'form_class': forms.EmailField,
            **kwargs,
        }) 
Example 71
Project: banruo   Author: yingshang   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        return super().formfield(**{
            'max_length': self.max_length,
            **({} if self.choices else {'widget': forms.Textarea}),
            **kwargs,
        }) 
Example 72
Project: repomaker   Author: f-droid   File: app.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(AppTranslationCreateForm, self).__init__(*args, **kwargs)
        self.fields['lang'] = CharField(required=True, min_length=2,
                                        widget=DataListTextInput(settings.LANGUAGES)) 
Example 73
Project: OwadeReborn   Author: CarlosLannister   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def launchNewView(request):
    class DDrescueForm(forms.Form):
        device = forms.CharField(max_length=30, initial="/dev/sd")
        overWrite = forms.BooleanField(initial=False, required=False)
        retry = forms.IntegerField(initial="3", required=False)

    launch = False
    if request.method == 'POST':
        form = DDrescueForm(request.POST)
        if form.is_valid():
            launch = True
            device = form.cleaned_data['device']
            overWrite = form.cleaned_data['overWrite']
            retry = form.cleaned_data['retry']
    else:
        form = DDrescueForm()

    if launch:
        if g_program.launch(NewHardDrive, device, overWrite, retry):
            return HttpResponseRedirect('launch')
        else:
            status = "Launch failure, a process is probably running"
    else:
        if g_program.available():
            status = "Choose a new Hard Drive to add to Owade"
        else:
            status = "A process is running, you may need to stop it"

    return render_to_response("launch_new.html", {
        'category':'Tasks',
        'page':'Add',
        'status':status,
        'form': form,
        'categoryList':categoryList,
        }, context_instance=RequestContext(request)) 
Example 74
Project: kobo-predict   Author: awemulya   File: forms.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, project, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(SiteBulkEditForm, self).__init__(*args, **kwargs)

        self.fields['sites'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=project.sites.all(),
        )

        for attr in project.site_meta_attributes:
            q_type = attr['question_type']
            q_name = attr['question_name']

            if q_type == 'Number':
                field = forms.FloatField()
            elif q_type == 'Date':
                field = forms.DateField()
            elif q_type == 'MCQ':
                options = attr.get('mcq_options') or []
                choices = [o.get('option_text') for o in options]
                choices = [(c, c) for c in choices]
                field = forms.ChoiceField(choices=choices)
            else:
                field = forms.CharField()

            self.fields[q_name] = field 
Example 75
Project: ops22   Author: spark8103   File: adminx.py    MIT License 5 votes vote down vote up
def save_forms(self):
        print dir(self.form_obj)
        #print self.form_obj.as_table()
        #print self.form_obj.cleaned_data
        #print self.form_obj.initial
        ss = os.popen("""python scripts/test.py""").read()
        #print ss
        self.form_obj.fields['res'] = forms.CharField(label=u'执行结果', widget=forms.Textarea(attrs={'readonly':'readonly'}))
        self.form_obj.cleaned_data['res'] = 234
        print self.form_obj.files.values()
        print self.form_obj.cleaned_data
        #self.message_user(ss) 
Example 76
Project: volttron-applications   Author: VOLTTRON   File: forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SiteForm, self).__init__(*args, **kwargs)
        self.fields['dr_programs'] = forms.ModelMultipleChoiceField(queryset=DRProgram.objects.all(), required=False)
        # self.fields['ven_id'] = forms.CharField(required=False)
        # self.fields['ven_name'] = forms.CharField(required=False) 
Example 77
Project: telemetry-analysis-service   Author: mozilla   File: mixins.py    Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cache = CachedFileCache()
        self.cached_filefields = OrderedDict()
        self.required_filefields = []

        field_order = []
        for name, field in list(self.fields.items()):
            # add any found field to the list of order items
            field_order.append(name)

            # in case it's a file input
            if isinstance(field, CachedFileField):
                # we'll use this later in the clean and save step
                self.cached_filefields[name] = field

                # store the field that are required so we can validate
                # them optionally in our clean method
                if field.real_required:
                    self.required_filefields.append(name)

                # get the name of the cache key field
                cachekey_input_name = self.cachekey_input_name(name)
                field_order.append(cachekey_input_name)

                # add the cache key field
                self.fields[cachekey_input_name] = forms.CharField(
                    max_length=32,
                    widget=CachedFileHiddenInput(),
                    initial=uuid.uuid4().hex,
                )

        self.order_fields(field_order) 
Example 78
Project: OwadeReborn   Author: CarlosLannister   File: views.py    GNU General Public License v3.0 4 votes vote down vote up
def analizeView(request):
    class AnalyzeForm(forms.Form):
        hardDrives = forms.ModelChoiceField(queryset=HardDrive.objects.all(), empty_label=None)
        report = forms.BooleanField(initial=False, required=False)
        dictionary = forms.CharField(initial=HASHCAT_DIR + "/rockyou.txt",required=False)
        chromePasswords = forms.BooleanField(initial=True,required=False)
        chromeHistory = forms.BooleanField(initial=True,required=False)
        firefoxPassword = forms.BooleanField(initial=True,required=False)
        firefoxHistory = forms.BooleanField(initial=True,required=False)
        wifi = forms.BooleanField(initial=True,required=False)
        outlook = forms.BooleanField(initial=True,required=False)

    launch = False
    if request.method == 'POST':
        form = AnalyzeForm(request.POST)
        if form.is_valid():
            launch = True
            hardDrive = form.cleaned_data['hardDrives']
            task = '5'
            report = form.cleaned_data['report']
            dictionary = form.cleaned_data['dictionary']
            chromePasswords = form.cleaned_data['chromePasswords']
            chromeHistory = form.cleaned_data['chromeHistory']
            firefoxPassword = form.cleaned_data['firefoxPassword']
            firefoxHistory = form.cleaned_data['firefoxHistory']
            wifi = form.cleaned_data['wifi']
            outlook = form.cleaned_data['outlook']

    else:
        form = AnalyzeForm()

    if launch:
        if g_program.task(task, hardDrive, report, dictionary, chromePasswords, chromeHistory,firefoxPassword,firefoxHistory, wifi, outlook):
            return HttpResponseRedirect('launch')
        else:
            status = "Launch failure, a process is probably running"
    else:
        if g_program.available():
            status = "Choose an hard drive to analyze"
        else:
            status = "A process is running, you may need to stop it"

    return render_to_response("analyze.html", {
        'category':'Tasks',
        'page':'Analyze',
        'status':status,
        'form': form,
        'categoryList':categoryList,
        }, context_instance=RequestContext(request)) 
Example 79
Project: OwadeReborn   Author: CarlosLannister   File: views.py    GNU General Public License v3.0 4 votes vote down vote up
def launchAnalyze(request):
    class AnalyzeForm(forms.Form):
        hardDrives = forms.ModelChoiceField(queryset=HardDrive.objects.all(), empty_label=None)
        tasks = forms.ChoiceField(choices=g_program.tasks_form_)
        report = forms.BooleanField(initial=False, required=False)
        dictionary = forms.CharField(initial=HASHCAT_DIR + "/rockyou.txt",required=False)
        chromePasswords = forms.BooleanField(initial=True,required=False)
        chromeHistory = forms.BooleanField(initial=True,required=False)
        firefoxPassword = forms.BooleanField(initial=True,required=False)
        firefoxHistory = forms.BooleanField(initial=True,required=False)
        wifi = forms.BooleanField(initial=True,required=False)
        outlook = forms.BooleanField(initial=True,required=False)

    launch = False
    if request.method == 'POST':
        form = AnalyzeForm(request.POST)
        if form.is_valid():
            launch = True
            hardDrive = form.cleaned_data['hardDrives']
            task = form.cleaned_data['tasks']
            report = form.cleaned_data['report']
            dictionary = form.cleaned_data['dictionary']
            chromePasswords = form.cleaned_data['chromePasswords']
            chromeHistory = form.cleaned_data['chromeHistory']
            firefoxPassword = form.cleaned_data['firefoxPassword']
            firefoxHistory = form.cleaned_data['firefoxHistory']
            wifi = form.cleaned_data['wifi']
            outlook = form.cleaned_data['outlook']

    else:
        form = AnalyzeForm()

    if launch:
        if task == "0":
            if g_program.task(task, hardDrive, report, chromePasswords, chromeHistory,firefoxPassword,firefoxHistory, wifi, outlook):
                return HttpResponseRedirect('launch')
            else:
                status = "Launch failure, a process is probably running"
        else:
            if g_program.task(task, hardDrive, report, dictionary, chromePasswords, chromeHistory,firefoxPassword,firefoxHistory, wifi, outlook):
                return HttpResponseRedirect('launch')
            else:
                status = "Launch failure, a process is probably running"
    else:
        if g_program.available():
            status = "Choose an hard drive to analyze"
        else:
            status = "A process is running, you may need to stop it"

    return render_to_response("launch_analyze.html", {
        'category':'Tasks',
        'page':'Analyze',
        'status':status,
        'form': form,
        'categoryList':categoryList,
        }, context_instance=RequestContext(request))


###############################################
##### Result overview
############################################### 
Example 80
Project: kobo-predict   Author: awemulya   File: forms.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def publish(self, user, id_string=None):
        if self.is_valid():
            # If a text (csv) representation of the xlsform is present,
            # this will save the file and pass it instead of the 'xls_file'
            # field.
            if 'text_xls_form' in self.cleaned_data\
               and self.cleaned_data['text_xls_form'].strip():
                csv_data = self.cleaned_data['text_xls_form']
                # "Note that any text-based field - such as CharField or
                # EmailField - always cleans the input into a Unicode string"
                # (https://docs.djangoproject.com/en/1.8/ref/forms/api/#django.forms.Form.cleaned_data).
                csv_data = csv_data.encode('utf-8')
                # requires that csv forms have a settings with an id_string or
                # form_id
                _sheets = csv_to_dict(StringIO(csv_data))
                try:
                    _settings = _sheets['settings'][0]
                    if 'id_string' in _settings:
                        _name = '%s.csv' % _settings['id_string']
                    else:
                        _name = '%s.csv' % _settings['form_id']
                except (KeyError, IndexError) as e:
                    raise ValueError('CSV XLSForms must have a settings sheet'
                                     ' and id_string or form_id')

                cleaned_xls_file = \
                    default_storage.save(
                        upload_to(None, _name, user.username),
                        ContentFile(csv_data))
            else:
                cleaned_xls_file = self.cleaned_data['xls_file']

            if not cleaned_xls_file:
                cleaned_url = self.cleaned_data['xls_url']
                if cleaned_url.strip() == u'':
                    cleaned_url = self.cleaned_data['dropbox_xls_url']
                cleaned_xls_file = urlparse(cleaned_url)
                cleaned_xls_file = \
                    '_'.join(cleaned_xls_file.path.split('/')[-2:])
                if cleaned_xls_file[-4:] != '.xls':
                    cleaned_xls_file += '.xls'
                cleaned_xls_file = \
                    upload_to(None, cleaned_xls_file, user.username)
                self.validate(cleaned_url)
                xls_data = ContentFile(urllib2.urlopen(cleaned_url).read())
                cleaned_xls_file = \
                    default_storage.save(cleaned_xls_file, xls_data)
            # publish the xls
            return publish_xls_form(cleaned_xls_file, user, id_string)