我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.HiddenInput()。
def preferences(request): class NotificationPreferenceForm(forms.ModelForm): event = forms.ChoiceField(choices=registry.get_event_choices(), disabled=True, widget=forms.HiddenInput()) method = forms.ChoiceField(choices=registry.get_method_choices(), disabled=True, widget=forms.HiddenInput()) business_lines = forms.ModelMultipleChoiceField(BusinessLine.authorization.for_user(request.user, 'incidents.view_incidents'), required=False) class Meta: fields = "__all__" formset = forms.inlineformset_factory(User, NotificationPreference, formset=NotificationPreferenceFormset, form=NotificationPreferenceForm) if request.method == 'POST': fs = formset(request.POST, instance=request.user) if fs.is_valid(): fs.save() return redirect('user:profile') else: fs = formset(instance=request.user) return render(request, "fir_async/preferences.html", {'formset': fs})
def update_base_fields(form_class, i18n_rules): labels_map = { 'country_area': i18n_rules.country_area_type, 'postal_code': i18n_rules.postal_code_type, 'city_area': i18n_rules.city_area_type} for field_name, area_type in labels_map.items(): field = form_class.base_fields[field_name] field.label = AREA_TYPE_TRANSLATIONS[area_type] hidden_fields = i18naddress.KNOWN_FIELDS - i18n_rules.allowed_fields for field_name in hidden_fields: if field_name in form_class.base_fields: form_class.base_fields[field_name].widget = forms.HiddenInput() country_field = form_class.base_fields['country'] country_field.choices = COUNTRY_CHOICES
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): if hasattr(self, 'wrapper_class'): context['wrapper_class'] = self.wrapper_class if self.attrs: if 'detail-class' in self.attrs: context['input_class'] = self.attrs['detail-class'] elif 'class' in self.attrs: context['input_class'] = self.attrs['class'] html = '' for field, result in self.results: context['result'] = result if field in form.fields: if form.fields[field].widget != forms.HiddenInput: context['field'] = form[field] html += loader.render_to_string(self.template, context) else: context['field'] = field html += loader.render_to_string(self.template, context) return html
def render_layout(self, form, context, template_pack=TEMPLATE_PACK): """ Copy any field label to the ``placeholder`` attribute. Note, this method is called when :attr:`layout` is defined. """ # Writing the label values into the field placeholders. # This is done at rendering time, so the Form.__init__() could update any labels before. # Django 1.11 no longer lets EmailInput or URLInput inherit from TextInput, # so checking for `Input` instead while excluding `HiddenInput`. for field in form.fields.values(): if field.label and \ isinstance(field.widget, (Input, forms.Textarea)) and \ not isinstance(field.widget, forms.HiddenInput): field.widget.attrs['placeholder'] = u"{0}:".format(field.label) return super(CompactLabelsCommentFormHelper, self).render_layout(form, context, template_pack=template_pack)
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs): super(ShowField, self).render(form, form_style, context, template_pack, extra_context, **kwargs) if extra_context is None: extra_context = {} if hasattr(self, 'wrapper_class'): extra_context['wrapper_class'] = self.wrapper_class if self.attrs: if 'detail-class' in self.attrs: extra_context['input_class'] = self.attrs['detail-class'] elif 'class' in self.attrs: extra_context['input_class'] = self.attrs['class'] html = '' for field, result in self.results: extra_context['result'] = result if field in form.fields: if form.fields[field].widget != forms.HiddenInput: extra_context['field'] = form[field] html += loader.render_to_string(self.template, extra_context) else: extra_context['field'] = field html += loader.render_to_string(self.template, extra_context) return html
def test_create_empty_form(self): """ Checks whether the 'model_class' attribute of the 'object_id' widget is None and the 'content_type' and 'object_id' widgets are not hidden in empty normal form """ # create an empty form form = forms.ImageAdminForm() # check whether the 'model_class' is None self.assertIsNone(form.fields['object_id'].widget.model_class) # check whether widgets are not hidden self.assertNotIsInstance( form.fields['content_type'].widget, django_forms.HiddenInput ) self.assertNotIsInstance( form.fields['object_id'].widget, django_forms.HiddenInput )
def test_create_empty_form_popup(self): """ Checks whether the 'content_type' and 'object_id' widgets are hidden in empty popup form (opened from another admin) """ # create an empty form with '_popup' initial form = forms.ImageAdminForm(initial={'_popup': True}) # check whether widgets are hidden self.assertIsInstance( form.fields['content_type'].widget, django_forms.HiddenInput ) self.assertIsInstance( form.fields['object_id'].widget, django_forms.HiddenInput )
def __init__(self, *args, **kwargs): # get 'initial' argument to determine whether the form # has been opened as a popup window initial = kwargs.get('initial') super(ImageAdminForm, self).__init__(*args, **kwargs) try: # get the class of the related model if it exists model_class = self.instance.content_type.model_class() except: # the related object is not specified model_class = None if initial and initial.get('_popup'): # do not show 'content_type' and 'object' id fields in # popup window to avoid changing related object since a popup # window could be opened from inline admin on the admin page # of existing object a new image will be attached to. self.fields['content_type'].widget = forms.HiddenInput() self.fields['object_id'].widget = forms.HiddenInput() else: # in general case set the model class to ObjectIdSelect self.fields['object_id'].widget.model_class = model_class
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) try: obj = self.instance.get_edited_object() except ObjectDoesNotExist: self.fields['object_link'].widget = forms.HiddenInput() self.fields['object_link'].help_text = '--//--' else: self.initial['object_link'] = self.instance.get_admin_url() self.fields['object_link'].widget.text = str(obj) if self.instance.user: admin_user_model = settings.AUTH_USER_MODEL.lower().replace('.', '_') self.initial['user_link'] = resolve_url('admin:{}_change'.format(admin_user_model), self.instance.user.pk) self.fields['user_link'].widget.text = str(self.instance.user) else: self.fields['user_link'].widget = forms.HiddenInput() self.fields['user_link'].help_text = '--//--'
def __init__(self, request, *args, **kwargs): kwargs.setdefault('auto_id', '') super().__init__(*args, **kwargs) self.initial['cmd'] = self.COMMAND self._initial_url(request, 'result_url', conf.RESULT_URL) self._initial_url(request, 'success_url', conf.SUCCESS_URL) self._initial_url(request, 'cancel_url', conf.CANCEL_URL) # ??????? ?????? ?? ????????? ??? ???? ????? for field in self.fields: self.fields[field].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, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', _('Submit'))) user = kwargs.pop('user', None) if hasattr(user,'id'): kwargs.update(initial={ 'submissionUser': user.id }) super(RevenueReportingForm,self).__init__(*args,**kwargs) self.fields['submissionUser'].widget = forms.HiddenInput() self.fields['invoiceNumber'].widget = forms.HiddenInput() self.fields["invoiceItem"] = InvoiceItemChoiceField(queryset=InvoiceItem.objects.none(),required=False) # re-order fields to put the associateWith RadioSelect first. newFields = OrderedDict() newFields['associateWith'] = self.fields['associateWith'] for key,field in self.fields.items(): if key not in ['associateWith']: newFields[key] = field self.fields = newFields
def set_choices(self, family): # There's probably a better way of doing this board_choices = [(brd.id, brd.name) for brd in Board.objects.filter(family=family)] self.fields['board_type'].choices = board_choices # class GuidedDeviceFlashForm(forms.Form): # DEVICE_FAMILY_CHOICES = GuidedDeviceSelectForm.DEVICE_FAMILY_CHOICES # # device_family = forms.ChoiceField(label="Device Family", # widget=forms.Select(attrs={'class': 'form-control', # 'data-toggle': 'select'}), # choices=DEVICE_FAMILY_CHOICES, required=True) # should_flash_device = forms.BooleanField(widget=forms.HiddenInput, required=False, initial=False) # #
def render(self, form, form_style, context): if hasattr(self, 'wrapper_class'): context['wrapper_class'] = self.wrapper_class if self.attrs: if 'detail-class' in self.attrs: context['input_class'] = self.attrs['detail-class'] elif 'class' in self.attrs: context['input_class'] = self.attrs['class'] html = '' for field, result in self.results: context['result'] = result if field in form.fields: if form.fields[field].widget != forms.HiddenInput: context['field'] = form[field] html += loader.render_to_string(self.template, context) else: context['field'] = field html += loader.render_to_string(self.template, context) return html
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 _get_form_widgets(self): """ Returns a dict of form widgets keyed by field name :return: Dict of field widgets """ widgets = super(OmniModelFormFieldView, self)._get_form_widgets() widgets.update({ 'name': forms.HiddenInput, 'widget_class': forms.HiddenInput, }) if self._field_is_required: widgets['required'] = forms.HiddenInput if issubclass(self.model, OmniRelatedField): widgets['related_type'] = forms.HiddenInput if len(self.model.FORM_WIDGETS) > 1: choices = map(lambda x: (x, x.rsplit('.')[-1]), self.model.FORM_WIDGETS) widgets['widget_class'] = forms.Select(choices=choices) return widgets
def test_form_fields_debug(self, m_conf): m_conf.DEBUG = True m_conf.SHOP_ID = conf.SHOP_ID form = self._get_form() for name, field in form.fields.items(): if name in conf.DISPLAY_FIELDS: self.assertNotIsInstance(field.widget, forms.HiddenInput) self.assertNotIsInstance(field.widget, readonly_widget.__class__) continue self.assertIsInstance(field.widget, readonly_widget.__class__) self.assertFalse(form.is_valid()) self.assertEqual(list(form.errors.keys()), ['__all__'])
def test_form_fields_no_debug(self, m_conf): m_conf.DEBUG = False m_conf.SHOP_ID = conf.SHOP_ID m_conf.DISPLAY_FIELDS = ['paymentType'] form = self._get_form() for name, field in form.fields.items(): if name in conf.DISPLAY_FIELDS: self.assertNotIsInstance(field.widget, forms.HiddenInput) self.assertNotIsInstance(field.widget, readonly_widget.__class__) continue self.assertIsInstance(field.widget, forms.HiddenInput) self.assertFalse(form.is_valid()) self.assertEqual(list(form.errors.keys()), ['__all__'])
def get_document_form(model): fields = model.admin_form_fields if 'collection' not in fields: # force addition of the 'collection' field, because leaving it out can # cause dubious results when multiple collections exist (e.g adding the # document to the root collection where the user may not have permission) - # and when only one collection exists, it will get hidden anyway. fields = list(fields) + ['collection'] return modelform_factory( model, form=BaseDocumentForm, fields=fields, widgets={ 'folder': forms.HiddenInput(), 'tags': widgets.AdminTagWidget, 'file': forms.FileInput() })
def test_render_hidden_fields(self): test_form = TestForm() test_form.helper = FormHelper() test_form.helper.layout = Layout( 'email' ) test_form.helper.render_hidden_fields = True html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 1) # Now hide a couple of fields for field in ('password1', 'password2'): test_form.fields[field].widget = forms.HiddenInput() html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 3) self.assertEqual(html.count('hidden'), 2) if django.get_version() < '1.5': self.assertEqual(html.count('type="hidden" name="password1"'), 1) self.assertEqual(html.count('type="hidden" name="password2"'), 1) else: self.assertEqual(html.count('name="password1" type="hidden"'), 1) self.assertEqual(html.count('name="password2" type="hidden"'), 1)
def __init__(self, data=None, files=None, ui_submission=False, **kwargs): super(MAASModelForm, self).__init__(data=data, files=files, **kwargs) if ui_submission: # Add the ui_submission field. Insert it before the other fields, # so that the field validators will have access to it regardless of # whether their fields were defined before or after this one. ui_submission_field = ( 'ui_submission', forms.CharField(widget=forms.HiddenInput(), required=False), ) # Django 1.6 and earlier use their own SortedDict class; 1.7 uses # the standard library's OrderedDict. The differences are # deprecated in 1.6, but to be on the safe side we'll use whichever # class is actually being used. dict_type = self.fields.__class__ self.fields = dict_type( [ui_submission_field] + list(self.fields.items()))
def __init__(self, request=None, *args, **kwargs): super(MachineForm, self).__init__(*args, **kwargs) # Even though it doesn't need it and doesn't use it, this form accepts # a parameter named 'request' because it is used interchangingly # with AdminMachineForm which actually uses this parameter. instance = kwargs.get('instance') self.set_up_architecture_field() # We only want the license key field to render in the UI if the `OS` # and `Release` fields are also present. if self.has_owner: self.set_up_osystem_and_distro_series_fields(instance) self.fields['license_key'] = forms.CharField( label="License Key", required=False, help_text=( "License key for operating system"), max_length=30) else: self.fields['license_key'] = forms.CharField( label="", required=False, widget=forms.HiddenInput())
def formfield(self, **kwargs): """Gets the form field associated with this field. Because this is a slug field which is automatically populated, it should be hidden from the form. """ defaults = { 'form_class': forms.CharField, 'required': False } defaults.update(kwargs) form_field = super().formfield(**defaults) form_field.widget = forms.HiddenInput() return form_field
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 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 __init__(self, *args, **kwargs): super(PasswordForm, self).__init__(*args, **kwargs) self.fields['email'].widget = forms.HiddenInput()
def __init__(self, *args, **kwargs): super(PyConLightningTalkProposalForm, self).__init__(*args, **kwargs) self.fields['audience_level'].widget = forms.HiddenInput() self.fields['audience_level'].initial = PyConLightningTalkProposal.AUDIENCE_LEVEL_NOVICE
def __init__(self, *args, **kwargs): super(PyConProposalForm, self).__init__(*args, **kwargs) self.fields['audience_level'].widget = forms.HiddenInput() self.fields['audience_level'].initial = PyConLightningTalkProposal.AUDIENCE_LEVEL_NOVICE
def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'widget_type': widgets = widget_manager.get_widgets(self.request.GET.get('page_id', '')) form_widget = WidgetTypeSelect(widgets) return forms.ChoiceField(choices=[(w.widget_type, w.description) for w in widgets], widget=form_widget, label=_('Widget Type')) if 'page_id' in self.request.GET and db_field.name == 'page_id': kwargs['widget'] = forms.HiddenInput field = super( UserWidgetAdmin, self).formfield_for_dbfield(db_field, **kwargs) return field
def get_field_attrs(self, __, db_field, **kwargs): if self.user_fields and db_field.name in self.user_fields: return {'widget': forms.HiddenInput} return __()
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): html = '' detail = form.detail for field in self.fields: if not isinstance(form.fields[field].widget, forms.HiddenInput): result = detail.get_field_result(field) html += loader.render_to_string( self.template, context={'field': form[field], 'result': result}) return html