Python django.forms.CharField() Examples

The following are 30 code examples for showing how to use django.forms.CharField(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: views.py    License: 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 2
Project: coursys   Author: sfu-fas   File: text.py    License: 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 3
Project: coursys   Author: sfu-fas   File: text.py    License: 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', '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 4
Project: coursys   Author: sfu-fas   File: forms.py    License: 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 5
Project: django-service-objects   Author: mixxorz   File: test_services.py    License: 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 6
Project: sphinxcontrib-django   Author: edoburu   File: test_docstrings.py    License: 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 7
Project: sphinxcontrib-django   Author: edoburu   File: test_docstrings.py    License: 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 8
Project: starthinker   Author: google   File: forms_json.py    License: 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 9
Project: pycon   Author: pythonitalia   File: forms.py    License: 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 10
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 11
Project: byro   Author: byro   File: registration.py    License: 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 12
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: 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
Project: Servo   Author: fpsw   File: repairs.py    License: 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 14
Project: django-places   Author: oscarmcm   File: forms.py    License: MIT License 5 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 15
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            text_field = forms.CharField()
            date_field = forms.DateField()
        self.form_class = MockForm
        self.form = self.form_class() 
Example 16
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            enabled_field = forms.CharField()
            disabled_field = forms.CharField(
                widget=forms.TextInput(attrs={'disabled': True}))
        self.form_class = MockForm
        self.form = self.form_class() 
Example 17
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            writable_field = forms.CharField()
            readonly_field = forms.CharField(
                widget=forms.TextInput(attrs={'readonly': True}))
        self.form_class = MockForm
        self.form = self.form_class() 
Example 18
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, event=None, *args, **kwargs):
        super(DonationEntryForm, self).__init__(*args, **kwargs)
        minDonationAmount = (
            event.minimumdonation if event is not None else Decimal('1.00')
        )
        self.fields['amount'] = forms.DecimalField(
            decimal_places=2,
            min_value=minDonationAmount,
            max_value=Decimal('100000'),
            label='Donation Amount (min ${0})'.format(minDonationAmount),
            widget=tracker.widgets.NumberInput(
                attrs={
                    'id': 'iDonationAmount',
                    'min': str(minDonationAmount),
                    'step': '0.01',
                }
            ),
            required=True,
        )
        self.fields['comment'] = forms.CharField(widget=forms.Textarea, required=False)
        self.fields['requestedvisibility'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedvisibility').choices,
            label='Name Visibility',
        )
        self.fields['requestedalias'] = forms.CharField(
            max_length=32, label='Preferred Alias', required=False
        )
        self.fields['requestedemail'] = forms.EmailField(
            max_length=128, label='Preferred Email', required=False
        )
        self.fields['requestedsolicitemail'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedsolicitemail').choices,
            label='Charity Email Opt In',
        ) 
Example 19
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, model, objects, *args, **kwargs):
        super(MergeObjectsForm, self).__init__(*args, **kwargs)
        self.model = model
        self.choices = []
        for objId in objects:
            choice_name = '#%d: ' % objId + str(self.model.objects.get(id=objId))
            self.choices.append((objId, choice_name))
        self.fields['root'] = forms.ChoiceField(choices=self.choices, required=True)
        self.fields['objects'] = forms.CharField(
            initial=','.join([str(i) for i in objects]), widget=forms.HiddenInput()
        ) 
Example 20
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(PrizeAcceptanceForm, self).__init__(*args, **kwargs)
        self.accepted = None

        if 'data' in kwargs and kwargs['data'] is not None:
            if 'accept' in kwargs['data']:
                self.accepted = True
            elif 'deny' in kwargs['data']:
                self.accepted = False

        self.fields['count'] = forms.ChoiceField(
            initial=self.instance.pendingcount,
            choices=list([(x, x) for x in range(1, self.instance.pendingcount + 1)]),
            label='Count',
            help_text='You were selected to win more than one copy of this prize, please select how many you would like to take, or press Deny All if you do not want any of them.',
        )
        if self.instance.pendingcount == 1:
            self.fields['count'].widget = forms.HiddenInput()
        self.fields['total'] = forms.IntegerField(
            initial=self.instance.pendingcount,
            validators=[positive],
            widget=forms.HiddenInput(),
        )
        self.fields['comments'] = forms.CharField(
            max_length=512,
            label='Notes',
            required=False,
            help_text='Please put any additional notes here (such as if you have the option of customizing your prize before it is shipped, or additional delivery information).',
            widget=forms.Textarea(attrs=dict(cols=40, rows=2)),
        ) 
Example 21
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def edit(request, ra_slug):
    appointment = get_object_or_404(RAAppointment, slug=ra_slug, deleted=False, unit__in=request.units)
    scholarship_choices, hiring_faculty_choices, unit_choices, project_choices, account_choices, program_choices = \
        _appointment_defaults(request.units, emplid=appointment.person.emplid)
    if request.method == 'POST':
        data = request.POST.copy()
        if data['pay_frequency'] == 'L':
            # force legal values into the non-submitted (and don't-care) fields for lump sum pay
            data['biweekly_pay'] = 1
            data['hourly_pay'] = 1
            data['hours'] = 1
            data['pay_periods'] = 1
        
        raform = RAForm(data, instance=appointment)
        if raform.is_valid():
            userid = raform.cleaned_data['person'].userid
            appointment = raform.save(commit=False)
            appointment.set_use_hourly(raform.cleaned_data['use_hourly'])
            appointment.save()
            l = LogEntry(userid=request.user.username,
                         description="Edited RA appointment %s." % appointment,
                         related_object=appointment)
            l.save()
            messages.success(request, 'Updated RA Appointment for ' + appointment.person.first_name + " " + appointment.person.last_name)
            return HttpResponseRedirect(reverse('ra:student_appointments', kwargs=({'userid': userid})))
    else:
        #The initial value needs to be the person's emplid in the form. Django defaults to the pk, which is not human readable.
        raform = RAForm(instance=appointment, initial={'person': appointment.person.emplid, 'use_hourly': appointment.use_hourly()})
        #As in the new method, choices are restricted to relevant options.
        raform.fields['person'] = forms.CharField(widget=forms.HiddenInput())
        raform.fields['hiring_faculty'].choices = hiring_faculty_choices
        raform.fields['scholarship'].choices = scholarship_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/edit.html', { 'raform': raform, 'appointment': appointment, 'person': appointment.person })


#Quick Reappoint, The difference between this and edit is that the reappointment box is automatically checked, and date information is filled out as if a new appointment is being created.
#Since all reappointments will be new appointments, no post method is present, rather the new appointment template is rendered with the existing data which will call the new method above when posting. 
Example 22
Project: coursys   Author: sfu-fas   File: text.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_entry_field(self, questionanswer=None, student=None):
        max_length = self.version.config.get('max_length', 1000)
        if questionanswer:
            initial = questionanswer.answer.get('data', '')
        else:
            initial = None

        field = forms.CharField(required=False, max_length=max_length, initial=initial)
        field.widget.attrs.update({'class': 'short-answer'})
        return field 
Example 23
Project: coursys   Author: sfu-fas   File: text.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_entry_field(self, questionanswer=None, student=None):
        max_length = self.version.config.get('max_length', 10000)
        lines = self.version.config.get('lines', 5)
        if questionanswer:
            initial = questionanswer.answer.get('data', '')
        else:
            initial = None

        field = forms.CharField(required=False, max_length=max_length, initial=initial,
                                widget=forms.Textarea(attrs={'rows': lines, 'cols': 100}))
        field.widget.attrs.update({'class': 'long-answer'})
        return field 
Example 24
Project: coursys   Author: sfu-fas   File: mc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, n=10, required=True, *args, **kwargs):
        self.n = n
        self.require_one = required
        fields = [
            forms.CharField(required=False, max_length=1000, initial='')
            for _ in range(self.n)
        ]
        fields += [
            forms.DecimalField(required=False, initial=0)
            for _ in range(self.n)
        ]
        super().__init__(fields=fields, require_all_fields=False, required=False, *args, **kwargs)
        self.force_display_required = True 
Example 25
Project: coursys   Author: sfu-fas   File: text.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        # before MarkupContentField, text_explanation held the contents; now text_explanation_0.
        explanation = self.config.get('text_explanation_0', self.config.get('text_explanation', ''))
        markup = self.config.get('text_explanation_1', 'creole')

        w = _ExplanationFieldWidget(explanation=explanation, markup=markup,
                                    attrs={'class': 'disabled', 'readonly': 'readonly'})
        c = forms.CharField(required=False,
            label=self.config['label'],
            help_text='',
            widget=w)

        return c 
Example 26
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        """
        Returns a Django Field for this field, to be filled in by the
        user. If filled is given, it is a FieldSubmission that must be
        used to populate initial data in the field.
        
        e.g. a CharField field.
        """
        raise NotImplementedError 
Example 27
Project: coursys   Author: sfu-fas   File: select.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, config=None):
            super(self.__class__, self).__init__(config)
            
            self.config = config

            if self.config:
                keys = [c for c in self.config if c.startswith("choice_") and self.config[c]]
                keys = sorted(keys, key=lambda choice: (int) (re.findall(r'\d+', choice)[0]))
            else:
                keys = []

            for k in keys:
                self.fields[k] = forms.CharField(required=False, label="Choice") 
Example 28
Project: coursys   Author: sfu-fas   File: select.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, config=None):
            super(self.__class__, self).__init__(config)

            self.config = config

            if self.config:
                keys = [c for c in self.config if c.startswith("choice_") and self.config[c]]
                keys = sorted(keys, key=lambda choice: (int) (re.findall(r'\d+', choice)[0]))
            else:
                keys = []                

            for k in keys:
                self.fields[k] = forms.CharField(required=False, label="Choice") 
Example 29
Project: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, max=20, min=2, other_required=False, *args, **kwargs):
        self.min = int(min)
        self.max = int(max)
        self.required = other_required
        kwargs['widget'] = CustomMultipleInputWidget(max=max, min=min)
        self.field_set = [fields.CharField() for _ in range(int(max))]

        super(CustomMultipleInputField, self).__init__(fields=self.field_set, *args, **kwargs) 
Example 30
Project: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        from onlineforms.forms import DividerFieldWidget

        return forms.CharField(required=False,
            widget=DividerFieldWidget(),
            label='',
            help_text='')