def render(self, form, request, step, context=None): "Renders the given Form object, returning an HttpResponse." old_data = request.POST prev_fields = [] if old_data: hidden = HiddenInput() # Collect all data from previous steps and render it as HTML hidden fields. for i in range(step): old_form = self.get_form(i, old_data) hash_name = 'hash_%s' % i prev_fields.extend([bf.as_hidden() for bf in old_form]) prev_fields.append(hidden.render(hash_name, old_data.get(hash_name, self.security_hash(request, old_form)))) return self.render_template(request, form, ''.join(prev_fields), step, context)
class PostForm(BasePostForm): enable_signature = BooleanField(widget=HiddenInput(), initial=True, label="", required=False)
def __init__(self, *args, **kwargs): super(ChangeForm, self).__init__(*args, **kwargs) self.fields['password'].widget = HiddenInput()
class Meta: model = Comment fields = ['author_nick', 'text', 'post'] widgets = {'post': HiddenInput()}
class Meta: fields = '__all__' model = Project widgets = { 'garden': HiddenInput(), }
class DocumentCreateForm(TranslationModelForm): """ The document upload form. """ permissions = forms.CharField(widget=HiddenInput(attrs={ 'name': 'permissions', 'id': 'permissions' }), required=True) resource = forms.CharField(required=False, label=_("Link to"), widget=TextInput(attrs={ 'name': 'title__contains', 'id': 'resource' })) class Meta: model = Document fields = ['title', 'doc_file', 'doc_url'] widgets = { 'name': HiddenInput(attrs={ 'cols': 80, 'rows': 20 }), } def clean_permissions(self): """ Ensures the JSON field is JSON. """ permissions = self.cleaned_data['permissions'] try: return json.loads(permissions) except ValueError: raise forms.ValidationError(_("Permissions must be valid JSON.")) def clean(self): """ Ensures the doc_file or the doc_url field is populated. """ cleaned_data = super(DocumentCreateForm, self).clean() doc_file = self.cleaned_data.get('doc_file') doc_url = self.cleaned_data.get('doc_url') if not doc_file and not doc_url: raise forms.ValidationError(_("Document must be a file or url.")) if doc_file and doc_url: raise forms.ValidationError( _("A document cannot have both a file and a url.")) return cleaned_data def clean_doc_file(self): """ Ensures the doc_file is valid. """ doc_file = self.cleaned_data.get('doc_file') if doc_file and not os.path.splitext(doc_file.name)[1].lower( )[1:] in settings.ALLOWED_DOCUMENT_TYPES: raise forms.ValidationError(_("This file type is not allowed")) return doc_file
def get_form(self): form = super().get_form() form.fields['order'].widget = HiddenInput() return form
def hide_field(self, field_name): self.fields[field_name].widget = HiddenInput()
def __init__(self, *args, **kwargs): self.pk = kwargs.pop("pk") super(SectionForm, self).__init__(*args, **kwargs) self.fields['child'].queryset = Child.objects.all() self.initial['child'] = Child.objects.filter(pk=self.pk).first() self.fields['child'].widget = HiddenInput()
def __init__(self, *args, **kwargs): super(SupportFilter, self).__init__(*args, **kwargs) self.filters['instance__name'].field.label = "Instance" self.filters['instance__service'].field.label = "Service" self.filters['instance__id'].field.widget = HiddenInput() self.filters['opened_by__username'].field.label = "User open"
class Meta: model = SymptomsMania fields = '__all__' widgets = {'clinical': HiddenInput()}
class Meta: model = Clinical fields = '__all__' widgets = {'participant': HiddenInput()}
class Meta: model = SymptomsBehaviour fields = '__all__' widgets = {'clinical': HiddenInput()}
class Meta: model = SymptomsDepression fields = '__all__' widgets = {'clinical': HiddenInput()}
class Meta: model = SymptomsHallucination fields = '__all__' widgets = {'clinical': HiddenInput()}
class Meta: model = PDFSong fields = ['song_number', 'song'] widgets = {'song': HiddenInput()}
def __init__(self, *args, **kwargs): self.pk = kwargs.pop("pk") super(CategoryForm, self).__init__(*args, **kwargs) self.fields['section'].queryset = Section.objects.all() self.initial['section'] = Section.objects.filter(pk=self.pk).first() self.fields['section'].widget = HiddenInput()
class EditCommentForm(Form): text = CharField(widget=Textarea(attrs={'id': 'hidden-textarea'})) comment_id = CharField(widget=HiddenInput()) similar_comment = CharField(widget=HiddenInput( attrs={'id': 'hidden-similar-comment'}))
def __init__(self, *args, **kwargs): self.pk = kwargs.pop("pk") super(UpdateSectionForm, self).__init__(*args, **kwargs) self.fields['child'].widget = HiddenInput()
class Meta: model = PySaleOrderDetail fields = [ 'sale_order', 'product', 'description', 'quantity', # 'measure_unit', # 'product_tax', 'amount_untaxed', 'discount', # 'amount_total', ] labels = { 'product': 'Producto', 'description': 'Descripción', 'quantity': 'Cantidad', # 'measure_unit': 'Unidad', # 'product_tax': 'Impuesto', 'amount_untaxed': 'Precio', 'discount': 'Descuento', # 'amount_total': 'Sub total', } widgets = { 'sale_order': HiddenInput(), 'product': autocomplete.ModelSelect2( url='product-autocomplete', forward=('sale_order', ), attrs={ 'class': 'form-control', 'data-placeholder': 'Seleccione un producto ...', 'style': 'width: 100%', }, ), 'description': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Descripción del producto ...', 'style': 'width: 100%', }, ), 'quantity': NumberInput(attrs={ 'class': 'form-control', 'data-placeholder': 'Cantidad del producto ...', 'style': 'width: 100%', }, ), # 'measure_unit': autocomplete.ModelSelect2( # url='measure-unit-autocomplete', # attrs={ # 'class': 'form-control', # 'data-placeholder': 'Seleccione un unidad ...', # 'style': 'width: 100%', # }, # ), # 'product_tax': autocomplete.ModelSelect2( # url='product-tax-autocomplete', # attrs={ # 'class': 'form-control', # 'data-placeholder': 'Seleccione un Impuesto ...', # 'style': 'width: 100%', # }, # ), 'amount_untaxed': NumberInput(attrs={ 'class': 'form-control', 'data-placeholder': 'Precio del producto ...', 'style': 'width: 100%', }, ), 'discount': NumberInput(attrs={ 'class': 'form-control', 'data-placeholder': 'Descuento ...', 'style': 'width: 100%', }, ), # 'amount_total': NumberInput( # attrs={ # 'class': 'form-control', # 'data-placeholder': 'Sub total ...', # 'style': 'width: 100%', # }, # ), }
def __init__(self, *args, **kwargs): super(PhotoForm, self).__init__(*args, **kwargs) self.fields['child'].widget = HiddenInput()
class ReservationForm(BaseNestedModelForm): RESOLVE = ( ("", "-------"), ("FORCE", "Force save"), ("SWAP", "Swap Appartments"), ) resolve = Field(label="Resolve", required=False, widget=HiddenInput()) period = ModelChoiceField(queryset=Period.objects.all(), required=False, label="Period") def __init__(self, *args, **kwargs): super(ReservationForm, self).__init__(*args, **kwargs) self.fields[ "owner"].queryset = MilitaryPerson.objects.prefetch_related( "rank").all().order_by("surname", "name") class Meta: model = Reservation fields = [ "res_type", "agent", "period", "check_in", "check_out", "owner", "appartment", "status", "persons", "book_ref", "telephone" ] def clean(self): super(ReservationForm, self).clean() def get_datetime(value): if value: y, m, d = map(int, value.split("-")) return datetime.date(y, m, d) period = self.cleaned_data.get("period", None) check_in = self.cleaned_data.get("check_in", None) check_out = self.cleaned_data.get("check_out", None) if period and (check_in or check_out): self._update_errors({ "period": ["You must provide either period or dates!"], }) if period: self.cleaned_data["check_in"] = period.start self.cleaned_data["check_out"] = period.end return self.cleaned_data def full_clean(self): self.cleaned_data = {} super(ReservationForm, self).full_clean() if self.instance.appartment: reservations = self.instance.appartment.reservations.filter( status__in=[RS_PENDING, RS_CONFIRM, RS_UNKNOWN]).exclude( id=self.instance.id) conflicting = [] for r in reservations: if (self.instance.status in (RS_PENDING, RS_CONFIRM, RS_UNKNOWN) and r.owner.id != self.instance.owner.id and r.inside( self.instance.check_in, self.instance.check_out)): conflicting.append(r) if conflicting: self.fields["resolve"] = ChoiceField( choices=ReservationForm.RESOLVE, required=False, label="Resolve") resolve = self.cleaned_data.get("resolve", None) print "resolving...." msgs = [ u"Conflicting Reservations:", ] if not resolve: self._update_errors({ "resolve": ["Choose a way to resolve conflict!"], NON_FIELD_ERRORS: msgs + [r.info for r in conflicting], }) if resolve == "FORCE": pass if resolve == "SWAP": if len(conflicting) > 1: self._update_errors({ "resolve": ["Swap is not supported for many conflicts!"], NON_FIELD_ERRORS: msgs + [r.info for r in conflicting], }) else: # TODO: find first available appartment appartment = None if self.instance.id: existing = Reservation.objects.get( id=self.instance.id) appartment = existing.appartment conflicting[0].appartment = appartment conflicting[0].save() msg = ( u"Conflicting Reservations:\n%s\nRESOLVE: %s\nChanged: %s\nNew/Updated: %s" % ("\n".join([c.info for c in conflicting]), resolve, conflicting[0].info, self.instance.info)) print msg.encode("utf-8")
class Meta: model = ArticleImage fields = ('image', 'caption', 'article', 'byline') widgets = {'article': HiddenInput(), 'byline': HiddenInput()}
def get_context_data(self, **kwargs): context = super(UploadImageView, self).get_context_data(**kwargs) # This sets the initial value for the field: context['form'].fields['user'].initial = self.request.user.pk context['form'].fields['user'].widget = HiddenInput() return context
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['order'].widget = HiddenInput()
def test_l10n_date_changed(self): """ Ensure that DateField._has_changed() with SelectDateWidget works correctly with a localized date format. Refs #17165. """ # With Field.show_hidden_initial=False ----------------------- b = GetDate( { 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '1', }, initial={'mydate': datetime.date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDate( { 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '2', }, initial={'mydate': datetime.date(2008, 4, 1)}) self.assertTrue(b.has_changed()) # With Field.show_hidden_initial=True ------------------------ b = GetDateShowHiddenInitial( { 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '1', 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1)) }, initial={'mydate': datetime.date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDateShowHiddenInitial( { 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1)) }, initial={'mydate': datetime.date(2008, 4, 1)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial( { 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1)) }, initial={'mydate': datetime.date(2008, 4, 22)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial( { 'mydate_year': '2008', 'mydate_month': '4', 'mydate_day': '22', 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 22)) }, initial={'mydate': datetime.date(2008, 4, 1)}) self.assertFalse(b.has_changed())
class ReporterRegistrationForm(Form): required_css_class = 'required' name = RegexField( regex="[^0-9.,\s@#$%&*~]*", max_length=80, error_message= _("Please enter a valid value containing only letters a-z or A-Z or symbols '`- " ), label=_("Name")) telephone_number = PhoneNumberField(required=True, label=_("Mobile Number")) geo_code = CharField(max_length=30, required=False, label=_("GPS Coordinates")) location = CharField(max_length=500, required=False, label=_("Name")) project_id = CharField(required=False, widget=HiddenInput()) DEVICE_CHOICES = ( ('sms', mark_safe( '<img src="/media/images/mini_mobile.png" /> <span>SMS</span>')), ('web', mark_safe( '<img src="/media/images/mini_computer.png" /> <span>Web</span>' + smartphone_icon()))) devices = MultipleChoiceField( label=_('Device'), widget=CheckboxSelectMultiple(), choices=DEVICE_CHOICES, initial=['sms'], required=False, ) email = EmailField( required=False, widget=TextInput(attrs=dict({'class': 'required'}, maxlength=75)), label=_("Email address"), error_messages={ 'invalid': _('Enter a valid email address. Example:[email protected]') }) short_code = CharField(required=False, max_length=12, label=_("Unique ID"), widget=TextInput(attrs=dict({ 'class': 'subject_field', 'disabled': 'disabled' }))) # Needed for telephone number validation org_id = None def __init__(self, org_id=None, *args, **kwargs): self.org_id = org_id super(ReporterRegistrationForm, self).__init__(*args, **kwargs) def _is_int(self, s): try: int(s) return True except ValueError: return False def _geo_code_format_validations(self, lat_long, msg): if len(lat_long) != 2: self._errors['geo_code'] = self.error_class([msg]) else: try: if not (-90 < float(lat_long[0]) < 90 and -180 < float(lat_long[1]) < 180): self._errors['geo_code'] = self.error_class([msg]) except Exception: self._errors['geo_code'] = self.error_class([msg]) def _geo_code_validations(self, b): msg = _( "Incorrect GPS format. The GPS coordinates must be in the following format: xx.xxxx,yy.yyyy. Example -18.8665,47.5315" ) geo_code_string = b.strip() geo_code_string = geo_code_string.replace(",", " ") geo_code_string = re.sub(' +', ' ', geo_code_string) if not is_empty(geo_code_string): lat_long = geo_code_string.split(" ") self._geo_code_format_validations(lat_long, msg) self.cleaned_data['geo_code'] = geo_code_string def clean(self): self.convert_email_to_lowercase() location = self.cleaned_data.get("location").strip() geo_code = self.cleaned_data.get("geo_code").strip() if not (bool(location) or bool(geo_code)): msg = _("Please fill out at least one location field correctly.") self._errors['location'] = self.error_class([msg]) self._errors['geo_code'] = self.error_class([msg]) if bool(geo_code): self._geo_code_validations(geo_code) return self.cleaned_data def clean_short_code(self): short_code = self.cleaned_data.get('short_code') if short_code: self.fields.get("short_code").widget.attrs.pop("disabled") if len(short_code) > 12: msg = _("Unique ID should be less than 12 characters") self.errors['short_code'] = self.error_class([msg]) if not re.match("^[a-zA-Z0-9]+$", short_code): msg = _("Only letters and numbers are valid") self.errors['short_code'] = self.error_class([msg]) return short_code def clean_telephone_number(self): """ Validate telephone number. This expects the dbm to be set on the form before trying to clean. """ organization = Organization.objects.get(org_id=self.org_id) mobile_number = self.cleaned_data.get('telephone_number') if organization.in_trial_mode: datasender_filter = DataSenderOnTrialAccount.objects.filter( mobile_number=(mobile_number)) if datasender_filter.exclude(organization=organization).exists(): self._errors['telephone_number'] = self.error_class([ _(u"Sorry, this number has already been used for a different DataWinners Basic account." ) ]) return mobile_number def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if not self.requires_web_access(): return None email = self.cleaned_data.get('email') if is_empty(email): msg = _('This field is required.') self._errors['email'] = self.error_class([msg]) return None if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError( _("This email address is already in use. Please supply a different email address." )) return self.cleaned_data['email'] def convert_email_to_lowercase(self): email = self.cleaned_data.get('email') if email is not None: self.cleaned_data['email'] = email.lower() def requires_web_access(self): devices = self.cleaned_data.get('devices') return devices.__contains__('web') def update_errors(self, validation_errors): mapper = { MOBILE_NUMBER_FIELD_CODE: 'telephone_number', GEO_CODE: GEO_CODE_FIELD_NAME } for field_code, error in validation_errors.iteritems(): self._errors[mapper.get(field_code)] = self.error_class([error])
class SaveForLaterForm(GovNotifyEmailActionMixin, forms.Form): email = forms.EmailField(label='Email address') url = forms.CharField(widget=HiddenInput(), disabled=True) expiry_timestamp = forms.CharField(widget=HiddenInput(), disabled=True)
class Meta: model = Ingredient widgets = {'recipes' HiddenInput()}
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get('instance', None): # it' a update of an existing subscription. For that we set the metadata field to readonly. self.fields['metadata'].widget = HiddenInput()
class Meta: model = MedicalHistory fields = '__all__' widgets = {'clinical': HiddenInput()}