我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.CharField()。
def __init__(self, *args, **kwargs): questions = sorted(list(kwargs.pop('questions')), key=attrgetter("number")) super(SurveyForm, self).__init__(*args, **kwargs) for i, question in enumerate(questions): if question.type == 'MC': vrs = question.variants self.fields['question_%s' % question.id] = forms.ChoiceField( label=question.text, choices=[(j, vrs[j]) for j in range(len(vrs))], widget=forms.RadioSelect, required=True) elif question.type == 'NR': self.fields['question_%s' % question.id] = forms.ChoiceField( choices=[(i, i) for i in range(1, 11)], label=question.text) elif question.type == 'TE': self.fields['question_%s' % question.id] = forms.CharField( max_length=512, required=True, widget=forms.TextInput(), label=question.text)
def test_create_unbound_form_field_types_1(self): form = PartyForm( schema_selectors=( {'name': None, 'selector': self.fixtures['org1'].pk}, {'name': 'project', 'value': self.fixtures['proj11'], 'selector': self.fixtures['proj11'].pk} ) ) assert form.attributes_field == 'attrs' assert 'name' in form.fields assert 'project' in form.fields assert 'attrs::dob' in form.fields assert isinstance(form.fields['attrs::dob'], forms.DateField) assert 'attrs::gender' in form.fields assert isinstance(form.fields['attrs::gender'], forms.CharField) assert 'attrs::education' in form.fields assert isinstance(form.fields['attrs::education'], forms.CharField) assert 'attrs::homeowner' in form.fields assert isinstance(form.fields['attrs::homeowner'], forms.BooleanField) assert len(form.fields) == 6
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # ??????? ?????? ?? ????????? for field in self.fields: self.fields[field].widget = forms.HiddenInput() if conf.TEST_MODE: self.fields['x_test_request'] = forms.CharField( required=False, initial='TRUE', widget=forms.HiddenInput, ) for fieldname in self.REQUIRE_INITIAL: value = self.initial.get(fieldname) if not value: raise ValueError('"%s" field requires initial value' % fieldname) self.initial['x_fp_timestamp'] = int(time.time()) self.initial['x_fp_hash'] = self.calc_signature()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['SignatureValue'].initial = self.calc_signature() # ??????? ?????? ?? ????????? for field in self.fields: self.fields[field].widget = forms.HiddenInput() if conf.TEST_MODE: self.fields['IsTest'] = forms.CharField( required=False, widget=forms.HiddenInput, ) for fieldname in self.REQUIRE_INITIAL: value = self.initial.get(fieldname) if not value: raise ValueError('"%s" field requires initial value' % fieldname)
def __init__(self, event, **kwargs): super().__init__(**kwargs) self.fields['submission_type'].queryset = SubmissionType.objects.filter(event=event) self.fields['title'].widget.attrs['placeholder'] = _('This is a serious talk') self.fields['abstract'].widget.attrs['placeholder'] = _('I am going to go into serious detail.') self.fields['description'].widget.attrs['placeholder'] = _( 'In my opinion, there is too much frivolity and chaos in the world. ' 'This is why I feel we should concentrate on seriousness, as the ' 'Serious Conference always does. I will detail good methods to ' 'introduce seriousness in silly places.' ) self.fields['notes'].widget.attrs['placeholder'] = _('I am a well-known speaker on this topic.') if not self.instance.pk: self.fields['speaker'] = forms.CharField( help_text=_('Add the email or nickname of the speaker holding the talk. They will be invited to create an account.') )
def __init__(self, *args, **kwargs): self.page=kwargs.pop('page') super(QuestionForm, self).__init__(*args, **kwargs) for p in Question.objects.filter(page=self.page): if p.id ==2: self.fields['url_field'] = forms.URLField(initial="http://",required = True) self.fields['url_field'].label = p.question self.fields['url_field'].page = p.page else: self.fields['extra_field_{index}'.format(index=p.id)] = forms.CharField(widget=forms.Textarea,required = True) self.fields['extra_field_{index}'.format(index=p.id)].label = p.question self.fields['extra_field_{index}'.format(index=p.id)].page = p.page
def get_context_data(self, **kwargs): articleid = int(self.kwargs[self.pk_url_kwarg]) comment_form = CommentForm() user = self.request.user if user.is_authenticated and not user.is_anonymous and user.email and user.username: comment_form.fields.update({ 'email': forms.CharField(widget=forms.HiddenInput()), 'name': forms.CharField(widget=forms.HiddenInput()), }) comment_form.fields["email"].initial = user.email comment_form.fields["name"].initial = user.username article_comments = self.object.comment_list() kwargs['form'] = comment_form kwargs['article_comments'] = article_comments kwargs['comment_count'] = len(article_comments) if article_comments else 0 kwargs['next_article'] = self.object.next_article kwargs['prev_article'] = self.object.prev_article return super(ArticleDetailView, self).get_context_data(**kwargs)
def form_invalid(self, form): article_id = self.kwargs['article_id'] article = Article.objects.get(pk=article_id) u = self.request.user if self.request.user.is_authenticated: form.fields.update({ 'email': forms.CharField(widget=forms.HiddenInput()), 'name': forms.CharField(widget=forms.HiddenInput()), }) user = self.request.user form.fields["email"].initial = user.email form.fields["name"].initial = user.username return self.render_to_response({ 'form': form, 'article': article })
def is_update(self): '''Mark all fields not listed in UPDATE_FIELDS as readonly''' for field in self.fields: if not field in self.UPDATE_FIELDS: # DP NOTE: readonly doesn't work for ChoiceFields, as # the user doesn't enter text, but selects a # value. Using a CharField doesn't allow them # to change the drop down, but still see the # selected value if isinstance(self.fields[field], forms.ChoiceField): self.fields[field] = forms.CharField() # DP NOTE: Using disabled means the values are not sent # back to the server, which means if there is a # validation error, the disabled fields will # be empty and also cause validation errors #self.fields[field].disabled = True #self.fields[field].widget.attrs['disabled'] = True self.fields[field].widget.attrs['readonly'] = True return self
def make_drawback_form(drawback): class DrawbackForm(forms.Form): def get_label(drawback): requirements = "" required_status = {} for status in HIGH_ROLLER_STATUS: required_status[status[0]] = status[1] if drawback.required_status in [HIGH_ROLLER_STATUS[2][0], HIGH_ROLLER_STATUS[3][0]]: requirements = "requires: {}".format(required_status[drawback.required_status]) return '{} ({}) {}'.format(drawback.name, drawback.description, requirements) label= get_label(drawback) eratta = drawback.eratta drawback_slug=str(drawback.slug) multiplicity_allowed=drawback.multiplicity_allowed; is_selected = forms.BooleanField(required=True) set_field_html_name(is_selected, drawback.form_name()) if drawback.detail_field_label is not "" and drawback.detail_field_label is not None: detail_text = forms.CharField(required=False, label=drawback.detail_field_label) set_field_html_name(detail_text, drawback.form_detail_name()) return DrawbackForm
def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) # Add honeypots self.honeypot_fieldnames = "address", "phone" self.honeypot_class = ''.join( random.choice(string.ascii_uppercase + string.digits) for __ in range(10)) self.honeypot_jsfunction = 'f' + ''.join( random.choice(string.ascii_uppercase + string.digits) for __ in range(10)) for fieldname in self.honeypot_fieldnames: self.fields[fieldname] = forms.CharField( widget=forms.TextInput(attrs={'class': self.honeypot_class}), required=False, )
def test_form_init(self, mock_get_user_model): mock_get_user_model.return_value = User initial_data = {'username': 'username', 'password': 'password', 'login_server': '202.141.80.10'} form = WebmailLoginForm(data=initial_data) self.assertIsInstance(form.fields['username'], forms.CharField) self.assertIsInstance(form.fields['password'], forms.CharField) self.assertIsInstance(form.fields['password'].widget, forms.PasswordInput) self.assertEqual(form.data.get('username'), initial_data.get('username')) self.assertEqual(form.data.get('password'), initial_data.get('password')) self.assertEqual(form.data.get('login_server'), initial_data.get('login_server')) self.assertEqual(form.port, poplib.POP3_SSL_PORT) self.assertEqual(form.username_field.verbose_name, User.USERNAME_FIELD)
def __init__(self, choices, validators, *args, **kwargs): """ :param validators: A dict that maps query type values to validators. """ if validators is None: validators = {} super(MultitypeQueryField, self).__init__(*args, **kwargs) self.fields = ( forms.ChoiceField(choices=choices), forms.CharField(min_length=1) ) self.widget = MultitypeQueryWidget( (forms.Select(choices=choices), forms.TextInput()) ) self.query_validators = validators
def __init__(self, *args, **kwargs): service_description = kwargs.pop('service_args') super(ServicePropertyForm, self).__init__(*args, **kwargs) args = service_description.get('args') opt_args = service_description.get('optargs') if args: for arg, descr in args: self.fields[arg] = forms.CharField(required=True, help_text=descr) if opt_args: for arg, descr in opt_args: self.fields[arg] = forms.CharField(required=False, help_text=descr) self.helper = FormHelper(self) self.helper.form_tag = False
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)
def __init__(self, *args, **kwargs): self._template = kwargs.pop('template', None) self._lookup = OrderedDict() self._created_fields = {} super(WorklistDefaultsForm, self).__init__(*args, **kwargs) # create a field for default values in each column of template for x in self._template.worklistcolumn_set.order_by('ordering', ): form_name = 'col.%s' % (x.pk, ) self.initial[form_name] = x.get_default() self.fields[form_name] = self._created_fields[form_name] = forms.CharField( help_text=x.help_text, initial=x.get_default(), label=str(x), required=False, widget=forms.TextInput(attrs={'size': 30}), ) self._lookup[form_name] = x
def __init__(self, *args, **kwargs): fields = [] defaults = { 'widget': self.widget, 'max_length': kwargs.pop('max_length', None), } self.locales = kwargs.pop('locales', [l[0] for l in 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
def add_port(self, port_name, direct_port, proxy_port, hostname): direct_field = forms.IntegerField(label=port_name + ' directly to port', initial=direct_port, min_value=1, max_value=2**16-1, required=False) self.fields[self.get_direct_field_name(port_name)] = direct_field proxy_field = forms.IntegerField(label=port_name + ' via reverse proxy to port', initial=proxy_port, min_value=1, max_value=2**16-1, required=False) self.fields[self.get_proxy_field_name(port_name)] = proxy_field hostname_field = forms.CharField(label=port_name + ' hostname ', initial=hostname, max_length=100, required=False) self.fields[self.get_hostname_field_name(port_name)] = hostname_field
def test_context_pollution(self): class ExampleForm(forms.Form): comment = forms.CharField() form = ExampleForm() form2 = TestForm() template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {{ form.as_ul }} {% crispy form2 %} {{ form.as_ul }} """) c = Context({'form': form, 'form2': form2}) html = template.render(c) self.assertEqual(html.count('name="comment"'), 2) self.assertEqual(html.count('name="is_company"'), 1)
def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) ordering = [] if EMAIL_AUTHENTICATION: self.fields["email"] = forms.EmailField( label = ugettext("Email"), ) ordering.append("email") else: self.fields["username"] = forms.CharField( label = ugettext("Username"), max_length = 30, ) ordering.append("username") ordering.extend(["password", "remember"]) self.fields.keyOrder = ordering
def test_form_local_path_field(self, redirect_form): """Form should have a 'local_path' field""" field = redirect_form.fields['local_path'] assert isinstance(field, forms.CharField) assert isinstance(field.widget, forms.TextInput) assert field.label == 'Fake local path' assert ( field.widget.attrs['placeholder'] == '/2017/04/04/we-are-all-doomed' )
def test_form_destination_url_field(self, redirect_form): """Form should have a 'destination_url' field""" field = redirect_form.fields['destination_url'] assert isinstance(field, forms.CharField) assert isinstance(field.widget, forms.TextInput) assert field.label == 'Destination URL' assert ( field.widget.attrs['placeholder'] == 'https://github.com/pawelad/fakester' )
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
def __init__(self, *args, **kwargs): extra = kwargs.pop('extra') super(JobMisClassify, self).__init__(*args, **kwargs) for i, job in enumerate(extra): self.fields['custom_%s' % i] = forms.ChoiceField(label=job, choices=INDUSTRY_CHOICES, required=False) # self.fields['custom_%s' % i] = forms.CharField(label=job, max_length=250, required=False)
def extra_answers(self): for name, value in self.cleaned_data.items(): if name.startswith('custom_'): yield (self.fields[name].label, value) # super(EducationMisClassify, self).__init__(*args, **kwargs) # for i in range(0, n): # self.fields["edu_correct %d" % i] = forms.ChoiceField(choices=MISCLASSIFY_SELECTION,) # edu_correct = forms.CharField(max_length=250)
def test_inline_edit_mod_textarea(self): class TempTable(MyTable): name = tables.Column(get_name, verbose_name="Verbose Name", sortable=True, form_field=forms.CharField( widget=forms.Textarea(), required=False), form_field_attributes={'class': 'test'}, update_action=MyUpdateAction) class Meta(object): name = "my_table" columns = ('id', 'name', 'value', 'optional', 'status') self.table = TempTable(self.request, TEST_DATA_2) name_col = self.table.columns['name'] name_col.auto = "form_field" row = self.table.get_rows()[0] name_cell = row.cells['name'] name_cell.inline_edit_mod = True # Check if is cell is rendered correctly. name_cell_rendered = name_cell.render() resp = http.HttpResponse(name_cell_rendered) self.assertContains(resp, '<textarea class="test" cols="40" id="name__1" ' 'name="name__1" rows="10">\r\ncustom object_1' '</textarea>', count=1, html=True)
def test_populate(self): """Create a FormsetDataTable and populate it with data.""" class TableForm(forms.Form): name = forms.CharField() value = forms.IntegerField() TableFormset = forms.formsets.formset_factory(TableForm, extra=0) class Table(table_formset.FormsetDataTable): formset_class = TableFormset name = tables.Column('name') value = tables.Column('value') class Meta(object): name = 'table' table = Table(self.request) table.data = TEST_DATA_4 formset = table.get_formset() self.assertEqual(2, len(formset)) form = formset[0] form_data = form.initial self.assertEqual('object_1', form_data['name']) self.assertEqual(2, form_data['value'])
def post(self, request, *args, **kwargs): self.extra.post(request, *args, **kwargs) form = self.view.get_form() if request.POST.get('form_cfg'): form.fields['form_cfg'] = CharField(widget=HiddenInput(), required=False) if form.is_valid(): self.form_cfg = form.cleaned_form_cfg return self.form_valid(form) else: return self.form_invalid(form)
def helper(self): """ The :class:`DefaultFormHelper` is instantiated only once when this helper property is accessed first. Assign your own form helper if you want to override the default behavior. This renders hidden fields and appends form actions by default. :return: Form helper instance """ if self._helper_instance is not None: return self._helper_instance if self.form_cfg: self.fields['form_cfg'] = CharField(widget=HiddenInput(), required=False) self.fields['form_cfg'].initial = json.dumps(self.form_cfg) try: self.init_add_fields() except AttributeError: pass helper = DefaultFormHelper(self) if 'form_action' in self.opts: helper.form_action = self.opts['form_action'] helper.render_hidden_fields = True helper.append_form_actions() self._helper_instance = helper return helper
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).lower(), }
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)
def __init__(self, *args, **kwargs): super(CharField, self).__init__(*args, **kwargs) self.validators.append(validators.MaxLengthValidator(self.max_length))
def check(self, **kwargs): errors = super(CharField, self).check(**kwargs) errors.extend(self._check_max_length_attribute(**kwargs)) return errors
def get_internal_type(self): return "CharField"
def get_prep_value(self, value): value = super(CharField, self).get_prep_value(value) return self.to_python(value)
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)
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)
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)
def __init__(self, lang='cpp', disable=False, code=None, theme='daylight', *args, **kwargs): super(EditorForm,self).__init__(*args, **kwargs) wg = AceWidget(mode=mode_map[lang], theme=theme, attrs={'readonly':'readonly'}) # TODO: Make the code field uneditable. self.fields['code'] = forms.CharField( widget=wg, disabled=disable, initial=code, )
def prepare_fields_for_attributes(self): for attribute in self.product_attributes: field_defaults = { 'label': attribute.name, 'required': False, 'initial': self.instance.get_attribute(attribute.pk)} if attribute.has_values(): field = CachingModelChoiceField( queryset=attribute.values.all(), **field_defaults) else: field = forms.CharField(**field_defaults) self.fields[attribute.get_formfield_name()] = field
def __init__(self, *args, **kwargs): super(VariantAttributeForm, self).__init__(*args, **kwargs) attrs = self.instance.product.product_class.variant_attributes.all() self.available_attrs = attrs.prefetch_related('values') for attr in self.available_attrs: field_defaults = { 'label': attr.name, 'required': True, 'initial': self.instance.get_attribute(attr.pk)} if attr.has_values(): field = CachingModelChoiceField( queryset=attr.values.all(), **field_defaults) else: field = forms.CharField(**field_defaults) self.fields[attr.get_formfield_name()] = field
def build_content_override_field(self): kwargs = { "label": "Content", "widget": MarkEdit(), "required": False, "initial": self.slot.content_override, } return forms.CharField(**kwargs)
def __init__(self, nplurals=1, attrs=None, *args, **kwargs): self.widget = MultiStringWidget(nplurals=nplurals, attrs=attrs) fields = [forms.CharField(strip=False) for i_ in range(nplurals)] super(MultiStringFormField, self).__init__(fields=fields, *args, **kwargs)
def __init__(self, *args, **kwargs): super(SourceDetailsForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) self.fields['bibtex'] = forms.CharField( widget=forms.Textarea(attrs={'class': 'bibtex'})) self.fields['bibtex'].initial = instance.bibtex for field in self.fields: self.fields[field].widget.attrs['readonly'] = True # if instance: # value = getattr(instance, field) # if value in ['', None]: # del self.fields[field]
def __init__(self, *args, **kwargs): if kwargs: profession = kwargs.pop("profession") # client is the parameter passed from views.py employment = kwargs.pop("employment") education = kwargs.pop("education") super(ProfileForm, self).__init__(*args, **kwargs) self.fields['profession'] = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'value': profession}), required=False) self.fields['employment'] = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'value': employment}), required=False) self.fields['education'] = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'value': education}), required=False) else: super(ProfileForm, self).__init__(*args, **kwargs)
def get_db_prep_save(self, value): "Returns a value suitable for storage into a CharField" if value == NOTSET: value = "" return str(value)
def __init__(self, *args, **kwargs): kwargs['required'] = False forms.CharField.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): kwargs['required'] = False kwargs['widget'] = forms.PasswordInput(render_value=self.render_value) forms.CharField.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): kwargs['required'] = False kwargs['widget'] = forms.Textarea() forms.CharField.__init__(self, *args, **kwargs)