예제 #1
0
class SecondaryMenuFormMixin(EntangledModelFormMixin):
    page_id = ChoiceField(
        label=_("CMS Page Id"),
        help_text=_(
            "Select a CMS page with a given unique Id (in advanced settings)."
        ),
    )

    offset = IntegerField(
        label=_("Offset"),
        initial=0,
        help_text=_("Starting from which child menu."),
    )

    limit = IntegerField(
        label=_("Limit"),
        initial=100,
        help_text=_("Number of child menus."),
    )

    class Meta:
        entangled_fields = {'glossary': ['page_id', 'offset', 'limit']}

    def __init__(self, *args, **kwargs):
        choices = [(p.reverse_id, str(p))
                   for p in Page.objects.filter(reverse_id__isnull=False,
                                                publisher_is_draft=False)]
        self.base_fields['page_id'].choices = choices
        super().__init__(*args, **kwargs)
예제 #2
0
class LoginForm(forms.Form):
    """
    Login form
    """

    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, request=None):
        super(LoginForm, self).__init__(data, files, auto_id, prefix, initial,\
            error_class, label_suffix, empty_permitted)
        self.request = request

    username = forms.CharField(label=_(u"用户名"), max_length=30)
    password = forms.CharField(widget=forms.PasswordInput(render_value=False, attrs={'class': 'middle', 'size': 20}))
    verify_img = forms.CharField(widget=CaptchaWidget())
    type = ChoiceField(widget=RadioSelect(attrs={'style': 'width:auto;'}), initial=0, choices=UserProfile.USER_TYPE)

    def clean_verify_img(self):
        """
        Validate that the verify code is valid.

        """
        verify_code = self.cleaned_data.get('verify_img', '')
        if verify_code == self.request.session.get(settings.NAME, ''):
            return verify_code
        raise forms.ValidationError(_(u'验证码错误。'))
예제 #3
0
class MapTileForm(AbstractMapForm):
    if settings.XGDS_MAP_SERVER_GDAL2TILES_ZOOM_LEVELS:
        minZoom = IntegerField(initial=12, label="Min Zoom")
        maxZoom = IntegerField(initial=20, label="Max Zoom", help_text="(UAV=23, Satellite=20)")
    
    resampleMethod = ChoiceField(choices=settings.XGDS_MAP_SERVER_GDAL_RESAMPLE_OPTIONS,
                                 label="Resampling")

    sourceFile = ResumableFileField(allowed_mimes=("image/tiff",),
                                    upload_url=lambda: reverse('uploadResumable'),
                                    chunks_dir=getattr(settings, 'FILE_UPLOAD_TEMP_DIR'),
                                    label="GeoTiff File"
                                    )

    def save(self, commit=True):
        instance = super(MapTileForm, self).save(commit=False)
        if not instance.creator:
            instance.creator = self.cleaned_data['username']
            instance.creation_time = datetime.datetime.now(pytz.utc)
        else:
            instance.modifier = self.cleaned_data['username']
            instance.modification_time = self.cleaned_data['username']
        instance.parent = self.getParentGroup()
        if commit:
            instance.save()
        
    
    class Meta(AbstractMapForm.Meta):
        model = MapTile
        exclude = ['creator', 'modifier', 'creation_time', 'modification_time', 'deleted', 'processed', 'minx', 'miny', 'maxx', 'maxy', 'resolutions']
예제 #4
0
    def __init__(self, booking, *args, **kwargs):
        super(BookingChoicesForm, self).__init__(*args, **kwargs)
        self.booking = booking

        # Adding form fields for each choice in the event
        choice_field_names = []
        for choice in booking.event.choices.all():
            field_name = (self.choice_id_stem + "{0}").format(choice.id)
            choice_field_names.append(field_name)
            options = list(choice.options.all())
            options.sort(key=self._scoreOption)
            options_choices = [(opt.id, opt.title) for opt in options]
            self.fields[field_name] = ChoiceField(label=choice.title,
                                                  choices=options_choices)

        # Define the Crispy Form helper
        self.helper = FormHelper()
        self.helper.form_method = "post"
        self.helper.form_action = reverse(
            "booking_update", kwargs={"booking_id": self.booking.id})
        self.helper.form_class = "form-horizontal"
        self.helper.label_class = "col-lg-3"
        self.helper.field_class = "col-lg-9"
        self.helper.layout = Layout(
            Div(*choice_field_names),
            FormActions(
                Submit("save", "Save", css_class="btn btn-success"),
                Reset("reset", "Reset", css_class="btn btn-warning"),
            ),
        )
예제 #5
0
class MailFilterForm(Form):
    filter = ChoiceField(label='Metoda filtrowania')

    def __init__(self, filter_methods, *args, **kwargs):
        self.filter_methods = filter_methods
        super().__init__(*args, **kwargs)
        self.fields['filter'].choices = [
            (k, v[1]) for k, v in self.filter_methods.items()
        ]

        self.helper = FormHelper(self)
        self.helper.include_media = False
        self.helper.layout.fields.append(
            FormActions(
                StrictButton('Filtruj',
                             type='submit',
                             css_class='btn-outline-primary mx-1 my-3 w-100'),
                css_class='text-right',
            ))

    @property
    def filter_id(self):
        return self.cleaned_data['filter']

    @property
    def filter_method(self):
        return self.filter_methods[self.cleaned_data['filter']][0]

    @property
    def filter_name(self):
        return self.filter_methods[self.cleaned_data['filter']][1]
예제 #6
0
class FinalizeGatewaySetupForm(Form):
    YES = 'Y'
    NO = 'N'

    YES_NO_CHOICES = (
        (YES, ugettext_lazy("Yes")),
        (NO, ugettext_lazy("No")),
    )

    name = TrimmedCharField(
        label=ugettext_lazy("Name"),
        required=True
    )
    set_as_default = ChoiceField(
        label=ugettext_lazy("Set as default gateway"),
        choices=YES_NO_CHOICES,
        required=True
    )

    def __init__(self, *args, **kwargs):
        super(FinalizeGatewaySetupForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form form-horizontal'
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-3 col-md-2'
        self.helper.layout = Layout(
            Div(
                hqcrispy.B3MultiField(
                    _("Name"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'name',
                            ng_model='name'
                        )
                    ),
                    get_rmi_error_placeholder('nameError'),
                    ng_class="{'has-error': nameError}"
                ),
                hqcrispy.B3MultiField(
                    _("Set as default gateway"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'set_as_default',
                            ng_model='setAsDefault',
                            style='margin-left: 0px;'
                        )
                    ),
                    get_rmi_error_placeholder('setAsDefaultError'),
                    ng_class="{'has-error': setAsDefaultError}"
                ),
                FormActions(
                    StrictButton(
                        _("Complete"),
                        id="id_create_backend",
                        css_class='btn-success',
                        ng_click='createBackend();'
                    )
                )
            )
        )
예제 #7
0
class PartsRequestForm(Form):
    # Ticket info
    priority = ChoiceField(label='Request Priority', error_messages={'required': 'Please select a priority'})

    # Request info
    printer = ModelChoiceField(queryset=None, empty_label="-------------", label='Printer', error_messages={'required': 'Please select a printer'})
    part = ChainedModelChoiceField('printer', reverse_lazy('printerrequests:chained_part'), Part, label='Part', error_messages={'required': 'Please select a part'})
    address = CharField(label='Location')

    def __init__(self, *args, **kwargs):
        super(PartsRequestForm, self).__init__(*args, **kwargs)

        self.fields['printer'].queryset = PrinterType.objects.filter(id__in=set(Part.objects.values_list('printer', flat=True)))
        self.fields["priority"].choices = PRIORITY_CHOICES

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.html5_required = True

        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-8 col-md-6'

        self.helper.layout = Layout(
            Fieldset(
                'Create a parts request',
                *self.fields
            ),
            FormActions(
                Submit('submit', 'Submit'),
            )
        )
예제 #8
0
파일: forms.py 프로젝트: rizac/eGSIM
class FormatForm(BaseForm):
    '''Form handling the validation of the format related argument in
    a request'''
    # py3 dict merge (see https://stackoverflow.com/a/26853961/3526777):
    __additional_fieldnames__ = {}

    format = ChoiceField(required=False, initial='json',
                         label='The format of the data returned',
                         choices=[('json', 'json'), ('text', 'text/csv')])

    text_sep = TextSepField(required=False, initial='comma',
                            label='The (column) separator character',
                            help_text=('Ignored if the requested '
                                       'format is not text'))
    text_dec = TextDecField(required=False, initial='period',
                            label='The decimal separator character',
                            help_text=('Ignored if the requested '
                                       'format is not text'))

    def clean(self):
        super().clean()
        tsep, tdec = 'text_sep', 'text_dec'
        # convert to symbols:
        if self.cleaned_data[tsep] == self.cleaned_data[tdec] and \
                self.cleaned_data['format'] == 'text':
            msg = _("'%s' must differ from '%s' in 'text' format" %
                    (tsep, tdec))
            err_ = ValidationError(msg, code='conflicting values')
            # add_error removes also the field from self.cleaned_data:
            self.add_error(tsep, err_)
            self.add_error(tdec, err_)

        return self.cleaned_data
예제 #9
0
파일: forms.py 프로젝트: zijie98/appstore
class AppScaffoldingForm(Form):
    name = CharField(max_length=80,
                     label=_('App name'),
                     validators=[validate_id],
                     help_text=_('The app name must be camel case e.g. MyApp'))
    platform = ChoiceField(choices=lazy(get_versions, list),
                           required=True,
                           label=_('Nextcloud version'))
    author_name = CharField(max_length=80, label=_('Author\'s full name'))
    author_email = EmailField(label=_('Author\'s e-mail'))
    author_homepage = URLField(label=_('Author\'s homepage'), required=False)
    issue_tracker = URLField(label=_('Issue tracker URL'),
                             required=True,
                             help_text=_('Bug reports and feature requests'))
    categories = MultipleChoiceField(required=True,
                                     label=_('Categories'),
                                     choices=lazy(get_categories, list),
                                     help_text=_('Hold down CTRL and click to '
                                                 'select multiple entries'))
    summary = CharField(
        max_length=256,
        label=_('Summary'),
        help_text=
        _('Short description of your app that will be rendered as short teaser'
          ))
    description = CharField(widget=Textarea,
                            label=_('Description'),
                            help_text=_('Full description of what your app '
                                        'does. Can contain Markdown.'))
예제 #10
0
class SMEForm(forms.Form):
    first_name = forms.CharField(label='First Name',
                                 max_length=255,
                                 required=True)
    last_name = forms.CharField(label='Last Name',
                                max_length=255,
                                required=True)
    email = forms.CharField(label='Email', max_length=255, required=True)
    review_limit = forms.IntegerField(label='Review Limit',
                                      initial=100,
                                      required=False)
    pay_rate = forms.DecimalField(max_digits=10,
                                  decimal_places=2,
                                  initial=0.00)
    job = ChoiceField([])
    region = RegionChoiceField(queryset=make_region_list_for_sme_manager(),
                               empty_label="(none)",
                               required=False)
    employer_user = EmployerUserChoiceField(
        queryset=make_employer_user_form_queryset(),
        label="Linked employer_user",
        required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['job'].choices = make_job_structure_for_dropdown(
            True, include_invisible=True)
예제 #11
0
 def margins(cls):
     form_fields = {}
     choices_format = [
         ('m-{}{}', _("4 sided margins ({})")),
         ('mx-{}{}', _("Horizontal margins ({})")),
         ('my-{}{}', _("Vertical margins ({})")),
         ('mt-{}{}', _("Top margin ({})")),
         ('mr-{}{}', _("Right margin ({})")),
         ('mb-{}{}', _("Bottom margin ({})")),
         ('ml-{}{}', _("Left margin ({})")),
     ]
     sizes = list(range(0, 6)) + ['auto']
     for bp in Breakpoint:
         if bp == Breakpoint.xs:
             choices = [(c.format('', s), format_lazy(l, s))
                        for c, l in choices_format for s in sizes]
             choices.insert(0, ('', _("No Margins")))
         else:
             choices = [(c.format(bp.name + '-', s), format_lazy(l, s))
                        for c, l in choices_format for s in sizes]
             choices.insert(
                 0,
                 ('',
                  format_lazy(_("Inherit margin from {}"), previous_label)))
         previous_label = bp.label
         form_fields['margins_{}'.format(bp.name)] = ChoiceField(
             label=format_lazy(_("Margins for {breakpoint}"),
                               breakpoint=bp.label),
             choices=choices,
             required=False,
             initial='',
         )
     return form_fields
예제 #12
0
 def paddings(cls):
     form_fields = {}
     choices_format = [
         ('p-{}{}', _("4 sided padding ({})")),
         ('px-{}{}', _("Horizontal padding ({})")),
         ('py-{}{}', _("Vertical padding ({})")),
         ('pt-{}{}', _("Top padding ({})")),
         ('pr-{}{}', _("Right padding ({})")),
         ('pb-{}{}', _("Bottom padding ({})")),
         ('pl-{}{}', _("Left padding ({})")),
     ]
     sizes = range(0, 6)
     for bp in Breakpoint:
         if bp == Breakpoint.xs:
             choices = [(c.format('', s), format_lazy(l, s))
                        for c, l in choices_format for s in sizes]
             choices.insert(0, ('', _("No Padding")))
         else:
             choices = [(c.format(bp.name + '-', s), format_lazy(l, s))
                        for c, l in choices_format for s in sizes]
             choices.insert(0, ('',
                                format_lazy(_("Inherit padding from {}"),
                                            previous_label)))
         previous_label = bp.label
         form_fields['padding_{}'.format(bp.name)] = ChoiceField(
             label=format_lazy(_("Padding for {breakpoint}"),
                               breakpoint=bp.label),
             choices=choices,
             required=False,
             initial='',
         )
     return form_fields
예제 #13
0
 def floats(cls):
     form_fields = {}
     choices_format = [
         ('float-{}none', _("Do not float")),
         ('float-{}left', _("Float left")),
         ('float-{}right', _("Float right")),
     ]
     for bp in Breakpoint:
         if bp == Breakpoint.xs:
             choices = [(c.format(''), l) for c, l in choices_format]
             choices.insert(0, ('', _("Unset")))
         else:
             choices = [(c.format(bp.name + '-'), l)
                        for c, l in choices_format]
             choices.insert(
                 0,
                 ('', format_lazy(_("Inherit float from {}"),
                                  previous_label)))
         previous_label = bp.label
         form_fields['float_{}'.format(bp.name)] = ChoiceField(
             label=format_lazy(_("Floats for {breakpoint}"),
                               breakpoint=bp.label),
             choices=choices,
             required=False,
             initial='',
         )
     return form_fields
예제 #14
0
class BroadcastMessageForm(forms.Form):

    text = CharField(label=ugettext_lazy("Text:"),
                     required=True,
                     max_length=160,
                     widget=forms.Textarea)
    to = ChoiceField(
        label=ugettext_lazy("To:"),
        choices=(("All", ugettext_lazy("All Data Senders")),
                 ("Associated",
                  ugettext_lazy("Data Senders associated to my project")),
                 ("Additional", ugettext_lazy("Other People"))),
        initial=("All"))
    others = CharField(label=ugettext_lazy("Other People:"),
                       max_length=160,
                       widget=forms.Textarea,
                       required=False)

    def __init__(self, *args, **kwargs):
        super(BroadcastMessageForm, self).__init__(*args, **kwargs)
        self.fields['text'].widget.attrs['watermark'] = ugettext_lazy(
            'Enter your SMS text')
        self.fields['text'].widget.attrs['id'] = 'sms_content'

    def clean_others(self):
        others = self.cleaned_data['others']
        return [
            number.strip() for number in others.split(',')
            if number.strip() != ''
        ]
예제 #15
0
class UserChangeForm(AuthUserChangeForm):
    language = ChoiceField(label=_("language"),
                           choices=[(k, _(v)) for k, v in settings.LANGUAGES],
                           initial=settings.LANGUAGE_CODE[:2])

    class Meta:
        model = User
예제 #16
0
    def __init__(self, *args, **kwargs):
        super(BlogForm, self).__init__(*args, **kwargs)
        self.fields["display_format"] = ChoiceField()
        self.fields["display_format"].choices = [
            ("structuredtext", "structuredtext"),
            ("markdown", "markdown"),
        ]
        self.fields["url"].required = False
        self.fields["summary"].required = False
        self.fields["proper_keywords"].required = False

        # 10 was default
        self.fields["text"].widget.attrs["rows"] = 20

        all_categories = dict(Category.objects.all().values_list("id", "name"))
        one_year = timezone.now() - datetime.timedelta(days=365)
        qs = (BlogItem.categories.through.objects.filter(
            blogitem__pub_date__gte=one_year).values("category_id").annotate(
                Count("category_id")).order_by("-category_id__count"))
        category_choices = []
        used = []
        for count in qs:
            pk = count["category_id"]
            combined = "{} ({})".format(all_categories[pk],
                                        count["category_id__count"])
            category_choices.append((pk, combined))
            used.append(pk)

        category_items = all_categories.items()
        for pk, name in sorted(category_items, key=lambda x: x[1].lower()):
            if pk in used:
                continue
            combined = "{} (0)".format(all_categories[pk])
            category_choices.append((pk, combined))
        self.fields["categories"].choices = category_choices
예제 #17
0
    def __init__(self, choices, initial=None, *args, **kwargs):
        assert not kwargs.get('required',
                              False), "required=True is not supported"

        allchoices = [x for x in choices]  # Force choices into a list.
        allchoices.append((OTHER_VAL, OTHER_PRES))
        self.widget = ChoiceOrOtherWidget(choices=allchoices)
        choice_initial, other_initial = None, None
        if initial is not None:
            # Match initial against one of the values
            if initial in [x for x, y in choices]:
                choice_initial = initial
            else:
                choice_initial = OTHER_VAL
                other_initial = initial

        fields = [
            ChoiceField(required=False, choices=allchoices),
            CharField(required=False)
        ]
        # Be careful not to make the initial value a tuple;
        # it's checked explicitly to be a list in MultiWidget's
        # render.
        super(ChoiceOrOtherField,
              self).__init__(fields,
                             initial=[choice_initial, other_initial],
                             *args,
                             **kwargs)
예제 #18
0
class ImportForm(Form):
    model = ChoiceField()
    csv = CsvFileField()

    def __init__(self,
                 app,
                 model,
                 data=None,
                 files=None,
                 auto_id='id_%s',
                 prefix=None,
                 initial=None):
        super(ImportForm, self).__init__(data, files, auto_id, prefix, initial)
        if self.data:
            app, model = self.data['model'].split(':')

        if model:
            m = "%s:%s" % (app, model)
            self.fields['model'].choices = [(m, m)]
            self.fields['model'].widget = Input({'readonly': 'readonly'})
            self.initial['model'] = m
        elif app:
            self.fields['model'].choices = _get_all_models(app)
        else:
            self.fields['model'].choices = _get_all_models()
예제 #19
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['start_url'] = forms.CharField(label='URL', required=True)
     self.fields['start_url'].widget.attrs['size'] = 80
     self.fields['job'] = ChoiceField(
         make_job_structure_for_dropdown(False, include_invisible=False))
     self.fields['job'].widget.attrs['class'] = 'browser-default'
예제 #20
0
class DomainDeploymentForm(forms.Form):
    city = CharField(label=ugettext_noop("City"), required=False)
    country = CharField(label=ugettext_noop("Country"), required=False)
    region = CharField(
        label=ugettext_noop("Region"),
        required=False,
        help_text=ugettext_noop(
            "e.g. US, LAC, SA, Sub-Saharan Africa, Southeast Asia, etc."))
    deployment_date = CharField(label=ugettext_noop("Deployment date"),
                                required=False)
    description = CharField(label=ugettext_noop("Description"),
                            required=False,
                            widget=forms.Textarea)
    public = ChoiceField(label=ugettext_noop("Make Public?"),
                         choices=tf_choices('Yes', 'No'),
                         required=False)

    def save(self, domain):
        try:
            domain.update_deployment(
                city=self.cleaned_data['city'],
                country=self.cleaned_data['country'],
                region=self.cleaned_data['region'],
                date=dateutil.parser.parse(
                    self.cleaned_data['deployment_date']),
                description=self.cleaned_data['description'],
                public=(self.cleaned_data['public'] == 'true'))
            return True
        except Exception:
            return False
예제 #21
0
class Parcel(SoColissimoSchema):
    soap_type_name = "ParcelVO"
    DELIVERY_MODES = ('DOM', 'RDV', 'BPR', 'ACP', 'CDI', 'A2P', 'MRL', 'CIT',
                      'DOS', 'CMT', 'BDP')

    weight = DecimalField(required=True,
                          min_value=0,
                          max_value=30,
                          decimal_places=2)
    DeliveryMode = ChoiceField(required=False,
                               choices=[(d, d) for d in DELIVERY_MODES])
    horsGabarit = BooleanField(required=False)

    insuranceValue = IntegerField(required=False, min_value=0)
    HorsGabaritAmount = IntegerField(required=False, min_value=0)
    Instructions = CharField(required=False)

    def clean_weight(self):
        """Ensure weight does not have a decimal part equals to 00"""
        weight = self.cleaned_data.get('weight')
        if weight % 1 == 0:
            weight = int(weight)
        return weight

    def clean_DeliveryMode(self):
        """ Default to "DOM" delivery mode if not specified """
        delivery_mode = self.cleaned_data.get('delivery_mode')
        if not delivery_mode:
            delivery_mode = "DOM"
        return delivery_mode

    def _set_constants(self, parcel):
        parcel.insuranceRange = "00"
        parcel.ReturnReceipt = False
        parcel.Recommendation = False
예제 #22
0
class HttpBackendForm(BackendForm):
    url = TrimmedCharField(label=ugettext_noop("URL"), )
    message_param = TrimmedCharField(
        label=ugettext_noop("Message Parameter"), )
    number_param = TrimmedCharField(
        label=ugettext_noop("Phone Number Parameter"), )
    include_plus = BooleanField(
        required=False,
        label=ugettext_noop("Include '+' in Phone Number"),
    )
    method = ChoiceField(
        label=ugettext_noop("HTTP Request Method"),
        choices=(("GET", "GET"), ("POST", "POST")),
    )
    additional_params = RecordListField(
        input_name="additional_params",
        label=ugettext_noop("Additional Parameters"),
    )

    def __init__(self, *args, **kwargs):
        if "initial" in kwargs and "additional_params" in kwargs["initial"]:
            additional_params_dict = kwargs["initial"]["additional_params"]
            kwargs["initial"]["additional_params"] = [{
                "name": key,
                "value": value
            } for key, value in additional_params_dict.items()]
        super(HttpBackendForm, self).__init__(*args, **kwargs)

    def clean_url(self):
        value = self.cleaned_data.get("url")
        if is_url_or_host_banned(value):
            raise ValidationError(_("Invalid URL"))
        return value

    def clean_additional_params(self):
        value = self.cleaned_data.get("additional_params")
        result = {}
        for pair in value:
            name = pair["name"].strip()
            value = pair["value"].strip()
            if name == "" or value == "":
                raise ValidationError("Please enter both name and value.")
            if name in result:
                raise ValidationError("Parameter name entered twice: %s" %
                                      name)
            result[name] = value
        return result

    @property
    def gateway_specific_fields(self):
        return crispy.Fieldset(
            _("HTTP Settings"),
            'url',
            'method',
            'message_param',
            'number_param',
            'include_plus',
            'additional_params',
        )
예제 #23
0
class FinalizeGatewaySetupForm(Form):
    YES = 'Y'
    NO = 'N'

    YES_NO_CHOICES = (
        (YES, ugettext_lazy("Yes")),
        (NO, ugettext_lazy("No")),
    )

    name = TrimmedCharField(label=ugettext_lazy("Name"), required=True)
    set_as_default = ChoiceField(label=ugettext_lazy("Set as default gateway"),
                                 choices=YES_NO_CHOICES,
                                 required=True)

    def __init__(self, *args, **kwargs):
        super(FinalizeGatewaySetupForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form form-horizontal'
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-3 col-md-2'
        self.helper.layout = Layout(
            Div(
                hqcrispy.B3MultiField(
                    _("Name"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'name',
                            data_bind='value: name',
                        )),
                    crispy.Div(
                        css_class="help-block",
                        data_bind="visible: nameError, text: nameError",
                    ),
                    data_bind="css: {'has-error': nameError}",
                ),
                hqcrispy.B3MultiField(
                    _("Set as default gateway"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'set_as_default',
                            data_bind='value: setAsDefault',
                            style='margin-left: 0px;')),
                    crispy.Div(
                        css_class="help-block",
                        data_bind=
                        "visible: setAsDefaultError, text: setAsDefaultError",
                    ),
                    data_bind="css: {'has-error': setAsDefaultError}",
                ),
                FormActions(
                    StrictButton(
                        "",
                        id="id_create_backend",
                        css_class='btn-primary',
                        data_bind=
                        "text: backendButtonText, click: createBackend, disable: creatingBackend,"
                        "css: {'btn-primary': !backendButtonError(), "
                        "'btn-danger': backendButtonError()}",
                    ))))
예제 #24
0
class BootstrapRowForm(ManageChildrenFormMixin, ModelForm):
    """
    Form class to add non-materialized field to count the number of children.
    """
    ROW_NUM_COLUMNS = (1, 2, 3, 4, 6, 12,)
    num_children = ChoiceField(choices=tuple((i, ungettext_lazy('{0} column', '{0} columns', i).format(i)) for i in ROW_NUM_COLUMNS),
        initial=3, label=_('Columns'),
        help_text=_('Number of columns to be created with this row.'))
예제 #25
0
 def __init__(self, *args, **kwargs):
     super(ReminderForm, self).__init__(*args, **kwargs)
     deadline_month = ChoiceField(
         choices=(tuple([(n, convert_to_ordinal(n)) for n in range(1, 31)] +
                        [(31, ugettext_lazy('Last Day'))])),
         widget=forms.Select,
         required=False)
     self.fields["deadline_month"] = deadline_month
예제 #26
0
class SMEContactForm(Form):
    employer_job = ChoiceField([])

    def __init__(self, employer, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields[
            'employer_job'].choices = make_employer_job_structure_for_dropdown(
                True, employer_id=employer.id)
예제 #27
0
def graph_form_factory(model):
    app_name = model._meta.app_label
    model_name = model.__name__

    model_fields = [(f.name, f.verbose_name) for f in model._meta.fields if not f.primary_key]
    graphs = [('PieChart', 'PieChart'), ('BarChart', 'BarChart')]
    model_fields.insert(0, ('', 'N/A'))
    class_name = "%s%sGraphForm" % (app_name, model_name)
    attrs = {'initial': {'app': app_name, 'model': model_name},
             '_selected_action': CharField(widget=MultipleHiddenInput),
             'select_across': BooleanField(initial='0', widget=HiddenInput, required=False),
             'app': CharField(initial=app_name, widget=HiddenInput),
             'model': CharField(initial=model_name, widget=HiddenInput),
             'graph_type': ChoiceField(label="Graph type", choices=graphs, required=True),
             'axes_x': ChoiceField(label="Group by and count by", choices=model_fields, required=True)}

    return DeclarativeFieldsMetaclass(str(class_name), (Form,), attrs)
예제 #28
0
class PalauteForm(ContactsForm):
    msg = CharField(label='Mitä haluat sanoa?', widget=Textarea)

    res = ChoiceField(choices=[(True, 'Haluan'), (False, 'En halua')],
                      label='Haluatko, että sinulle vastataan?',
                      widget=RadioSelect)

    captcha = ReCaptchaField()
class RenderTemplateFormMixin(EntangledModelFormMixin):
    render_template = ChoiceField(
        label=_("Render template"),
        help_text=_("Use alternative template for rendering this plugin."),
    )

    class Meta:
        entangled_fields = {'glossary': ['render_template']}
예제 #30
0
 def __init__(self, *args, **kwargs):
     super(GenericForm, self).__init__(*args, **kwargs)
     backends = get_backend_choices()
     self.fields['backend'] = ChoiceField(
         choices=backends,
         initial=backends[0][0] if len(backends) else '',
         widget=widgets.HiddenInput,
     )
예제 #31
0
 def __init__(self, initial=None, *args, **kwargs):
     ChoiceField.__init__(self, IMPORT_FILE_TYPE_CHOICES, initial, *args, **kwargs)
예제 #32
0
 def __init__(self, initial=None, *args, **kwargs):
     ChoiceField.__init__(self, UnicodeEncodingField.CHOICES, initial, *args, **kwargs)