Python django.forms.CharField() Examples

The following are 30 code examples of django.forms.CharField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.forms , or try the search function .
Example #1
Source File: text.py    From coursys with GNU General Public License v3.0 7 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):

        self.min_length = 0
        self.max_length = 0

        if self.config['min_length'] and int(self.config['min_length']) > 0:
            self.min_length = int(self.config['min_length'])
        if self.config['max_length'] and int(self.config['max_length']) > 0:
            self.max_length = int(self.config['max_length'])

        c = forms.CharField(required=self.config['required'],
            widget=forms.Textarea(attrs={'cols': '60', 'rows': self.config.get('rows', '15')}),
            label=self.config['label'],
            help_text=self.config['help_text'],
            min_length=self.min_length,
            max_length=self.max_length)

        if fieldsubmission:
            c.initial = fieldsubmission.data['info']

        return c 
Example #2
Source File: forms.py    From pycon with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        fields = []
        defaults = {"widget": self.widget, "max_length": kwargs.pop("max_length", None)}
        self.locales = kwargs.pop("locales", settings.LANGUAGES)
        self.one_required = kwargs.get("required", True)
        require_all_fields = kwargs.pop("require_all_fields", False)
        kwargs["required"] = False
        kwargs["widget"] = kwargs["widget"](
            locales=self.locales, field=self, **kwargs.pop("widget_kwargs", {})
        )
        defaults.update(**kwargs)
        for lngcode, _ in self.locales:
            defaults["label"] = "%s (%s)" % (defaults.get("label"), lngcode)
            field = forms.CharField(**defaults)
            field.locale = lngcode
            fields.append(field)
        super().__init__(fields=fields, require_all_fields=False, *args, **kwargs)
        self.require_all_fields = require_all_fields 
Example #3
Source File: test_docstrings.py    From sphinxcontrib-django with Apache License 2.0 6 votes vote down vote up
def test_add_form_fields(self):
        """Form fields should be mentioned."""
        lines = []
        docstrings._add_form_fields(SimpleForm, lines)
        self.assertEqual(
            lines,
            [
                "**Form fields:**",
                "",
                "* ``user``: User (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``user2``: User2 (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``user3``: User3 (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``test1``: Test1 (:class:`~django.forms.fields.CharField`)",
                "* ``test2``: Test2 (:class:`~django.forms.fields.CharField`)",
            ],
        ) 
Example #4
Source File: test_docstrings.py    From sphinxcontrib-django with Apache License 2.0 6 votes vote down vote up
def test_model_init_params(self):
        """Model __init__ gets all fields as params."""
        lines = []
        docstrings._add_model_fields_as_params(self.app, SimpleModel, lines)
        self.assertEqual(
            lines,
            [
                ":param id: Id",
                ":type id: AutoField",
                ":param user: User",
                ":type user: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param user2: User2",
                ":type user2: ForeignKey to"
                " :class:`~sphinxcontrib_django.tests.test_docstrings.User2`",
                ":param user3: User3",
                ":type user3: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param dummy_field: Dummy field",
                ":type dummy_field: CharField",
            ],
        ) 
Example #5
Source File: forms_json.py    From starthinker with Apache License 2.0 6 votes vote down vote up
def get_field_kind(field):
  if field['kind'] == 'string':
    return forms.CharField(max_length=255, required=False)
  elif field['kind'] == 'email':
    return forms.EmailField(max_length=255, required=False)
  elif field['kind'] == 'integer':
    return forms.IntegerField(required=False)
  elif field['kind'] == 'boolean':
    return forms.BooleanField(required=False)
  elif field['kind'] == 'text':
    return forms.CharField(widget=forms.Textarea(), required=False)
  elif field['kind'] == 'choice':
    return forms.ChoiceField(choices=map(lambda c: (c,c), field['choices']))
  elif field['kind'] == 'timezones':
    return TimezoneField()
  elif field['kind'] == 'authentication':
    return SwitchField('user', 'service', required=True)
  elif field['kind'] == 'json':
    return JsonField(required=False)
  elif field['kind'] == 'integer_list':
    return CommaSeparatedIntegerField(required=False)
  elif field['kind'] == 'string_list':
    return CommaSeparatedCharField(required=False)
  else:
    return forms.CharField(max_length=255, required=False) 
Example #6
Source File: text.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        self.min_length = 0
        self.max_length = 0

        if self.config['min_length'] and int(self.config['min_length']) > 0:
            self.min_length = int(self.config['min_length'])
        if self.config['max_length'] and int(self.config['max_length']) > 0:
            self.max_length = int(self.config['max_length'])

        c = forms.CharField(required=self.config['required'],
            widget=forms.Textarea(attrs={'cols': '60', 'rows': self.config.get('rows', '3')}),
            label=self.config['label'],
            help_text=self.config['help_text'],
            min_length=self.min_length,
            max_length=self.max_length)

        if fieldsubmission:
            c.initial = fieldsubmission.data['info']

        return c 
Example #7
Source File: test_cluster_form.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_formfield_callback(self):

        def formfield_for_dbfield(db_field, **kwargs):
            # a particularly stupid formfield_callback that just uses Textarea for everything
            return CharField(widget=Textarea, **kwargs)

        class BandFormWithFFC(ClusterForm):
            formfield_callback = formfield_for_dbfield

            class Meta:
                model = Band
                fields = ['name']

        form = BandFormWithFFC()
        self.assertEqual(Textarea, type(form['name'].field.widget))
        self.assertEqual(Textarea, type(form.formsets['members'].forms[0]['name'].field.widget)) 
Example #8
Source File: forms.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def add_extra_questions(self, event):
        if 'extra_questions' in event.config and len(event.config['extra_questions']) > 0:
            extra_fields = []
            for question in event.config['extra_questions']:
                extra_fields.append(question)
                if 'extra_questions' in self.instance.config and question in self.instance.config['extra_questions']:
                    self.fields[question] = \
                        forms.CharField(label=question,widget=forms.Textarea,
                                        initial=self.instance.config['extra_questions'][question])
                else:
                    self.fields[question] = forms.CharField(label=question, widget=forms.Textarea)
            # We want to move the extra questions *before* the waivers, for neatness' sake.
            field_list = (self._meta.fields)
            # We got the original list of fields, add our extra questions in the spot before two before last.
            field_list[len(field_list) - 2:len(field_list) - 2] = extra_fields
            # Re-order the fields to that list.
            self.order_fields(field_list) 
Example #9
Source File: registration.py    From byro with Apache License 2.0 6 votes vote down vote up
def build_default_field(self, field, model):
        choices = getattr(field, "choices", None)
        if choices:
            return forms.ChoiceField(
                required=False,
                label=_("Default value"),
                choices=[(None, "-----------")] + list(choices),
            )
        if not (model is Member and field.name == "number"):
            if isinstance(field, models.CharField):
                return forms.CharField(required=False, label=_("Default value"))
            elif isinstance(field, models.DecimalField):
                return forms.DecimalField(
                    required=False,
                    label=_("Default value"),
                    max_digits=field.max_digits,
                    decimal_places=field.decimal_places,
                )
            elif isinstance(field, models.DateField):
                return forms.CharField(required=False, label=_("Other/fixed date")) 
Example #10
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def new_student(request, userid):
    person = get_object_or_404(Person, find_userid_or_emplid(userid))
    semester = Semester.next_starting()
    semesterconfig = SemesterConfig.get_config(request.units, semester)
    student = get_object_or_404(Person, find_userid_or_emplid(userid))
    initial = {'person': student.emplid, 'start_date': semesterconfig.start_date(), 'end_date': semesterconfig.end_date(), 'hours': 80 }
    scholarship_choices, hiring_faculty_choices, unit_choices, project_choices, account_choices, program_choices = \
        _appointment_defaults(request.units, emplid=student.emplid)
    gss = GradStudent.objects.filter(person=student)
    if gss:
        gradstudent = gss[0]
        initial['sin'] = gradstudent.person.sin()
    
    raform = RAForm(initial=initial)
    raform.fields['person'] = forms.CharField(widget=forms.HiddenInput())
    raform.fields['scholarship'].choices = scholarship_choices
    raform.fields['hiring_faculty'].choices = hiring_faculty_choices
    raform.fields['unit'].choices = unit_choices
    raform.fields['project'].choices = project_choices
    raform.fields['account'].choices = account_choices
    raform.fields['program'].choices = program_choices
    return render(request, 'ra/new.html', { 'raform': raform, 'person': person })

#Edit RA Appointment 
Example #11
Source File: test_services.py    From django-service-objects with MIT License 6 votes vote down vote up
def test_extra_fields(self):

        class FooModelService(ModelService):
            two = forms.CharField()

            class Meta:
                model = FooModel
                fields = '__all__'

            def process(self):
                pass

        f = FooModelService()

        field_names = list(six.iterkeys(f.fields))
        self.assertEqual(2, len(field_names))
        self.assertEqual('one', field_names[0])
        self.assertEqual('two', field_names[1]) 
Example #12
Source File: forms.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        active = kwargs.pop('active', None)
        request = kwargs.pop('request', None)
        super(AdminUserForm, self).__init__(*args, **kwargs)

        if not kwargs.get('instance', None):
            self.fields['is_active'].initial = True

        if active == 'add':
            self.fields['password_1'] = forms.CharField(widget=forms.PasswordInput, label="Password")
            self.fields['password_2'] = forms.CharField(widget=forms.PasswordInput, label="Repeat password")

        if request and not request.user.is_admin:
            self.fields.pop('is_staff', None)
            self.fields.pop('is_admin', None)

        if request and not request.user.is_superuser:
            self.fields.pop('is_superuser') 
Example #13
Source File: forms.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        settings = kwargs.pop('settings', None)
        super(GeneratedPluginSettingForm, self).__init__(*args, **kwargs)

        for field in settings:

            object = field['object']
            if field['types'] == 'char':
                self.fields[field['name']] = forms.CharField(widget=forms.TextInput(), required=False)
            elif field['types'] == 'rich-text' or field['types'] == 'text' or field['types'] == 'Text':
                self.fields[field['name']] = forms.CharField(widget=forms.Textarea, required=False)
            elif field['types'] == 'json':
                self.fields[field['name']] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                                                       choices=field['choices'],
                                                                       required=False)
            elif field['types'] == 'number':
                self.fields[field['name']] = forms.CharField(widget=forms.TextInput(attrs={'type': 'number'}))
            elif field['types'] == 'select':
                self.fields[field['name']] = forms.CharField(widget=forms.Select(choices=field['choices']))
            elif field['types'] == 'date':
                self.fields[field['name']] = forms.CharField(
                    widget=forms.DateInput(attrs={'class': 'datepicker'}))
            elif field['types'] == 'boolean':
                self.fields[field['name']] = forms.BooleanField(
                    widget=forms.CheckboxInput(attrs={'is_checkbox': True}),
                    required=False)

            self.fields[field['name']].initial = object.processed_value
            self.fields[field['name']].help_text = object.setting.description 
Example #14
Source File: forms.py    From conf_site with MIT License 5 votes vote down vote up
def build_content_override_field(self):
        kwargs = {
            "label": "Content",
            "required": False,
            "initial": self.slot.content_override,
        }
        return forms.CharField(**kwargs) 
Example #15
Source File: test_form_mixins.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_set_standard_field_no_question(self):
        form_mixin = form_mixins.AttributeFormMixin()
        form_mixin.project = self.project
        form_mixin.fields = {'name': CharField()}
        questionnaire = q_factories.QuestionnaireFactory(project=self.project)
        q_factories.QuestionFactory.create(
            name='party_name',
            questionnaire=questionnaire,
            label={'en': 'Name', 'de': 'Name'})
        form_mixin.set_standard_field('name',)

        assert hasattr(form_mixin.fields['name'], 'labels_xlang') is False 
Example #16
Source File: form_mixins.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean(self):
        cleaned_data = super().clean()
        for name in self.fields:
            field = self.fields[name]
            if type(field) is not CharField:
                continue

            value = cleaned_data.get(name)
            if not sanitize_string(value):
                self.add_error(name, ValidationError(SANITIZE_ERROR))

        return cleaned_data 
Example #17
Source File: test_form_mixins.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_set_standard_field(self):
        form_mixin = form_mixins.AttributeFormMixin()
        form_mixin.project = self.project
        form_mixin.fields = {'party_name': CharField()}
        questionnaire = q_factories.QuestionnaireFactory(project=self.project)
        q_factories.QuestionFactory.create(
            name='party_name',
            questionnaire=questionnaire,
            label={'en': 'Name', 'de': 'Name'})
        form_mixin.set_standard_field('party_name')

        assert 'en="Name"' in form_mixin.fields['party_name'].labels_xlang
        assert 'de="Name"' in form_mixin.fields['party_name'].labels_xlang 
Example #18
Source File: forms.py    From tom_base with GNU General Public License v3.0 5 votes vote down vote up
def extra_field_to_form_field(field_type):
    if field_type == 'number':
        return forms.FloatField(required=False)
    elif field_type == 'boolean':
        return forms.BooleanField(required=False)
    elif field_type == 'datetime':
        return forms.DateTimeField(required=False)
    elif field_type == 'string':
        return forms.CharField(required=False, widget=forms.Textarea)
    else:
        raise ValueError(
            'Invalid field type {}. Field type must be one of: number, boolean, datetime string'.format(field_type)
        ) 
Example #19
Source File: test_form_mixins.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_set_standard_field_set_field_name(self):
        form_mixin = form_mixins.AttributeFormMixin()
        form_mixin.project = self.project
        form_mixin.fields = {'name': CharField()}
        questionnaire = q_factories.QuestionnaireFactory(project=self.project)
        q_factories.QuestionFactory.create(
            name='party_name',
            questionnaire=questionnaire,
            label={'en': 'Name', 'de': 'Name'})
        form_mixin.set_standard_field('party_name', field_name='name')

        assert 'en="Name"' in form_mixin.fields['name'].labels_xlang
        assert 'de="Name"' in form_mixin.fields['name'].labels_xlang 
Example #20
Source File: fields.py    From prospector with GNU General Public License v3.0 5 votes vote down vote up
def formfield(self, form_class=forms.CharField, **kwargs):
        kwargs['widget'] = forms.PasswordInput

        return super().formfield(form_class=form_class, **kwargs) 
Example #21
Source File: __init__.py    From bioforum with MIT License 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}
        if not self.choices:
            defaults['widget'] = forms.Textarea
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example #22
Source File: __init__.py    From bioforum with MIT License 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().formfield(**defaults) 
Example #23
Source File: __init__.py    From bioforum with MIT License 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 #24
Source File: __init__.py    From bioforum with MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example #25
Source File: __init__.py    From bioforum with MIT License 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 #26
Source File: forms.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        org = kwargs.pop("org")
        org_fields = Field.get_all(org).order_by("label")

        fields = (
            forms.ModelChoiceField(queryset=org_fields, required=False, to_field_name="key"),
            forms.CharField(max_length=64),
        )
        widgets = (fields[0].widget, fields[1].widget)

        super(FieldTestField, self).__init__(fields, *args, **kwargs)

        self.widget = FieldTestWidget(widgets) 
Example #27
Source File: models.py    From anytask with MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
    defaults = {
      'form_class': forms.CharField,
      'widget': CKEditorWidget(config=self.config, filemanager_url=self.filemanager_url)
    }
    defaults.update(kwargs)
    return super(CKEditorField, self).formfield(**defaults) 
Example #28
Source File: models.py    From anytask with MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
    defaults = {
      'form_class': forms.CharField,
      'widget': CKEditorWidget(config=self.config, filemanager_url=self.filemanager_url)
    }
    defaults.update(kwargs)
    return super(CKEditorField, self).formfield(**defaults) 
Example #29
Source File: mixins.py    From telemetry-analysis-service with 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 #30
Source File: forms.py    From kobo-predict with 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