Esempio n. 1
0
class ResourceForm(forms.Form):
    method = forms.ChoiceField(
        choices=(
            ('GET', 'GET'),
            ('POST', 'POST')
        ),
        widget=forms.RadioSelect(
            attrs={
                'class': 'custom-control-input',
            } 
        ),
        label='Тип запроса'
    )
    resource_type = forms.ChoiceField(
        choices=(
            ('poet', 'Poet'),
            ('poem', 'Poem')
        ),
        widget=forms.RadioSelect(
            attrs={
                'class': 'custom-control-input',
            } 
        ),
        label='Поэт или стихотворения'
    )
    data = forms.JSONField(
        widget=forms.Textarea(
            attrs={
                'class': 'form-control',
                'rows': 8,
                'placeholder': '{"input": "your json data"}'
            }
        ),
        required=False,
    )
Esempio n. 2
0
    def __init__(self, *args, **kwargs):

        self.helper = FormHelper()
        self.helper.form_class = 'no-asterisk'
        self.helper.form_tag = True
        self.helper.form_method = 'POST'
        self.helper.form_action = ''

        super(AddProductForm, self).__init__(*args, **kwargs)

        sku = forms.CharField(
            label="SKU"
        )

        name = forms.CharField(
            label="Name",
        )

        attributes = forms.JSONField(
            label="Attributes",
        )

        self.fields['sku'] = sku
        self.fields['name'] = name
        self.fields['attributes'] = attributes

        self.helper.layout = Layout(
            'sku',
            'name',
            'attributes',
            HTML("""<br><button type="submit" class="btn btn-primary">Add Product</button>""")
        )
Esempio n. 3
0
class UXActionLogForm(forms.Form):
    """Handles the arguments passed to the log UX action view.
    """

    action_type = forms.CharField()
    experiment = forms.CharField(required=False)
    data = forms.JSONField(required=False)
    class GuideSectionForm(forms.Form):
        title = forms.CharField(label='Section Title',
                                required=True,
                                max_length=380)
        slug = forms.SlugField(label='Slug',
                                required=True,
                                max_length=80)
        position = forms.IntegerField(initial=0,
                                      validators=[MinValueValidator(1)],
                                      help_text=position_help_text)
        header_level = forms.IntegerField(initial=1,
                                          validators=[MaxValueValidator(6), MinValueValidator(1)],
                                          help_text=header_help_text)
        is_hidden = forms.BooleanField(label='Hide from non-admins?',
                                       help_text="If checked, non-admins will not be able to view this article. Great for WIPs!",
                                       required=False)
        content = forms.CharField(label='Content',
                                  widget=TinyMCE(attrs={'cols': 80, 'rows': 30}, mce_attrs=GUIDE_SECTION_TINYMCE_SETTINGS),
                                  max_length=73000,
                                  required=False,
                                  help_text='write the content for the section.')

        tags = forms.JSONField(label='tags',
                              required=False,
                               widget=forms.TextInput,
                              help_text='["tags", "for searching in", "navbar"]')
class AdvSearchDownloadForm(forms.Form):
    """
    Advanced search download form for any advanced search data.
    """

    qryjson = forms.JSONField(widget=forms.HiddenInput())

    def clean(self):
        """This override of super.clean is so we can reconstruct the search inputs upon form_invalid in views.py"""
        self.saved_data = self.cleaned_data
        return self.cleaned_data
Esempio n. 6
0
class EmailConfirmationForm(forms.Form):
    name = forms.CharField(max_length=100, required=True, label='Nombre')
    surname = forms.CharField(max_length=100, required=True, label='Apellido')
    phone_number = forms.CharField(max_length=20, help_text='Ej. 3415778972.', label='Teléfono')
    location = forms.ChoiceField(choices = choices, label='Localidad')
    customer_address = forms.CharField(max_length=100, label='Domicilio')
    email = forms.EmailField(required=False, help_text='Agregue email si desea recibir orden por correo electrónico.')
    gift = forms.BooleanField(label='Para Regalar!', required=False)
    order_items = forms.JSONField(widget=forms.HiddenInput()) 
    captcha = CaptchaField()

    def clean_location(self):
        value = self.cleaned_data.get('location')
        return dict(self.fields['location'].choices)[value]
Esempio n. 7
0
class InstanceForm(ModelForm):

    name = forms.CharField(
        label="Name",
        required=True,
        widget=forms.TextInput(attrs={'class': 'form-control'}))

    spec = forms.JSONField(
        label="JSON Spec",
        required=False,
        widget=forms.Textarea(attrs={'class': 'form-control'}))

    class Meta:
        model = Instance
        fields = ["name", "spec"]
class CreateTournament(forms.ModelForm):
    tournament_date = forms.DateField(required=False)
    tournament_time = forms.TimeField(required=False)
    picture = forms.ImageField(required=False)
    center = forms.UUIDField(required=False)
    format = forms.UUIDField(required=False)
    entry_fee = forms.FloatField(required=False)
    total_games = forms.IntegerField(required=False)
    placements = forms.JSONField(required=False)
    class Meta:
        model = Tournament
        fields = ['name', 'description', 'datetime', 'picture', 'center', 'format', 'entry_fee', 'total_games', 'placements']

    def clean(self):
        cleaned_data = super().clean()
        return cleaned_data
Esempio n. 9
0
class PostForm(forms.Form):
    author = forms.ModelChoiceField(queryset=Author.objects.all(),
                                    empty_label="Указать автора")
    tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
    title = forms.CharField(max_length=128)
    slug = forms.SlugField(max_length=64)  #.create_slug
    content = forms.JSONField(max_length=2048)
    publish = forms.ChoiceField(choices=((False, "Не публиковать"),
                                         (True, "Опубликовать")))

    author.widget.attrs['class'] = "form-control"
    tags.widget.attrs['class'] = "form-control"
    title.widget.attrs['class'] = "form-control"
    slug.widget.attrs['class'] = "form-control"
    content.widget.attrs['class'] = "form-control"
    publish.widget.attrs['class'] = "form-control"
Esempio n. 10
0
class WorkoutTrackerForm(forms.ModelForm):
    class Meta:
        model = WorkoutTracker
        fields = ('session_name',
                  'workout',
                  'session_reps',
                  'session_average_rpe',
                  'session_volume',
                  'session_notes',
                  )

    session_name = forms.CharField()
    workout = forms.JSONField(widget=forms.HiddenInput())
    session_reps = forms.IntegerField(widget=forms.HiddenInput())
    session_average_rpe = forms.FloatField(widget=forms.HiddenInput())
    session_volume = forms.FloatField(widget=forms.HiddenInput())
    session_notes = forms.Textarea()
Esempio n. 11
0
class TestApi(forms.Form):
    api_url = forms.URLField(label='Url')
    api_header = forms.JSONField(label='Header',
                                 initial={
                                     "Content-type": "application/json",
                                     "Origin": "*",
                                     "Authorization": ""
                                 })
    # api_type_choices = [('JSON', 'JSON'), ('XML', 'XML')]
    api_request_type_choices = [('POST', 'POST'), ('PUT', 'PUT')]
    api_request_type = forms.ChoiceField(choices=api_request_type_choices,
                                         label='Request type')
    # api_type = forms.ChoiceField(choices=api_request_type_choices, label='Request type')
    api_body = forms.CharField(widget=forms.Textarea, label='Body')

    def clean_api_header(self):
        api_header = self.cleaned_data['api_header']
        try:
            api_header["Content-type"]
        except KeyError:
            raise forms.ValidationError('''Please give a Content-type tag''')

    def clean_api_body(self):
        api_header = self['api_header']
        html_string = str(api_header).replace('&quot;', '"')
        api_header_clean = json.loads(
            html_string[html_string.index("{"):html_string.index("}") + 1])
        print(type(api_header_clean))
        api_body = self.cleaned_data['api_body']
        if "Content-type" in api_header_clean.keys():
            if "json" in api_header_clean["Content-type"].lower():
                try:
                    json.loads(api_body)
                except json.decoder.JSONDecodeError:
                    raise forms.ValidationError(
                        '''Please enter a valid jason object list using " as quotations for keys and values and ' inside request and respond packets where quotes are needed'''
                    )
            elif "xml" in api_header_clean["Content-type"].lower():
                try:
                    xdm.parseString(api_body)
                except xdm.xml.parsers.expat.ExpatError:
                    raise forms.ValidationError(
                        '''Please enter a valid xml packet''')
Esempio n. 12
0
class importFlawsForm(forms.Form):
    iData = forms.JSONField(label='Import Data', max_length=100000)

    def clean_iData(self):
        data = self.cleaned_data['iData']
        output = []
        try:
            for key in data.keys():
                newFlaw = VF()
                newFlaw.name = data[key]['name']
                newFlaw.description = data[key]['description']
                newFlaw.value = data[key]['value'].lower()
                newFlaw.type = data[key]['type'].lower()
                if data[key]['type'].lower() == 'social status':
                    newFlaw.type = 'socialStatus'
                newFlaw.virtueOrFlaw = 'flaw'
                output.append(newFlaw)
            return output
        except:
            raise ValidationError('JSON data is improperly formatted.')
Esempio n. 13
0
class DistroIntegrationForm(forms.Form):
    token = forms.CharField(required=True)
    version = forms.CharField(required=True)
    run_id = forms.CharField(required=True)
    distro = forms.CharField(required=True)
    epoch = forms.CharField(required=True)
    artifact_name = forms.CharField(required=True)
    pr_number = forms.IntegerField(required=False)
    package_versions = forms.JSONField(required=True)

    def is_authorized(self, gate):
        token = conf.settings.INTEGRATION_REPO['token']
        if token != self.cleaned_data['token']:
            raise PermissionDenied

        from_channel_base = conf.settings.BASE_CONDA_PATH / self.cleaned_data[
            'epoch']
        if gate == conf.settings.GATE_STAGED:
            from_channel = str(from_channel_base / conf.settings.GATE_TESTED)
        elif gate == conf.settings.GATE_PASSED:
            from_channel = str(from_channel_base / conf.settings.GATE_STAGED /
                               self.cleaned_data['distro'])
        else:
            raise ValueError('invalid gate: %s' % (gate, ))

        config = DistroBuildCfg(
            version=self.cleaned_data['version'],
            run_id=self.cleaned_data['run_id'],
            package_name=self.cleaned_data['distro'],
            epoch_name=self.cleaned_data['epoch'],
            artifact_name=self.cleaned_data['artifact_name'],
            github_token=conf.settings.GITHUB_TOKEN,
            pr_number=self.cleaned_data['pr_number'],
            owner=conf.settings.INTEGRATION_REPO['owner'],
            repo=conf.settings.INTEGRATION_REPO['repo'],
            package_versions=self.cleaned_data['package_versions'],
            gate=gate,
            from_channel=from_channel,
        )

        return config
Esempio n. 14
0
class UpdatePaymentForm(forms.Form):
    action = forms.CharField()
    data = forms.JSONField()

    def save(self):
        cd = self.cleaned_data
        mp = mercadopago.SDK(settings.MERCADO_PAGO_ACCESS_TOKEN)
        if cd["action"] == "payment.updated":
            mercado_pago_id = cd["data"]["id"]
            payment = Payment.objects.get(mercado_pago_id=mercado_pago_id)
            payment_mp = mp.payment().get(mercado_pago_id)

            payment.mercado_pago_status = payment_mp["response"]["status"]
            payment.mercado_pago_status_detail = payment_mp["response"]["status_detail"]

            if payment_mp["response"]["status"] == "approved":
                payment.order.paid = True
            else:
                payment.order.paid = False

            payment.order.save()
            payment.save()
Esempio n. 15
0
class importAbilitiesForm(forms.Form):
    iData = forms.JSONField(label='Import Data', max_length=100000)

    def clean_iData(self):
        data = self.cleaned_data['iData']
        output = []
        try:
            for key in data.keys():
                newAbility = Ability()
                newAbility.name = data[key]['name']
                newAbility.description = data[key]['description']
                if data[key]['type'][0] == '(':
                    newAbility.type = data[key]['type'][1:-1].lower()
                else:
                    newAbility.type = data[key]['type'].lower()
                newAbility.needTraining = data[key]['needTraining']
                specialties = data[key]['specialties']
                output.append([newAbility, specialties])

            return output
        except:
            raise ValidationError('JSON data is improperly formatted.')
Esempio n. 16
0
class AddChecksheet(forms.Form):
    name = forms.CharField(label='Checksheet Name', max_length=200)
    description = forms.CharField(widget=forms.Textarea)

    data = forms.JSONField()
Esempio n. 17
0
class BaseConnectorConfigForm(forms.Form):
    def __init__(self, *args, **kwargs):
        # get the instance connector
        self.connector = kwargs.pop("connector")
        # pass the connector config as initial
        super().__init__(*args, **kwargs, initial=self.connector.config)

    def save(self):
        for field in self.cleaned_data.keys():
            if self.cleaned_data[field]:
                self.connector.config[field] = self.cleaned_data[field]
            else:
                if self.connector.config.get(field):
                    # if is a boolean field, mark as false
                    # else, delete
                    if type(self.fields[field]) == forms.fields.BooleanField:
                        self.connector.config[field] = False
                    else:
                        del self.connector.config[field]
            self.connector.save()

    open_room = forms.BooleanField(
        required=False, initial=True, help_text="Uncheck to avoid creating a room"
    )
    timezone = forms.CharField(help_text="Timezone for this connector", required=False)
    force_close_message = forms.CharField(
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Force this message on close",
        required=False,
    )
    outcome_attachment_description_as_new_message = forms.BooleanField(
        required=False,
        help_text="This might be necessary for the bot to react accordingly",
    )
    add_agent_name_at_close_message = forms.BooleanField(required=False)
    overwrite_custom_fields = forms.BooleanField(
        required=False, help_text="overwrite custom fields on new visitor registration"
    )
    supress_visitor_name = forms.BooleanField(
        required=False,
        help_text="do not overwrite visitor name with connector visitor name",
    )
    include_connector_status = forms.BooleanField(
        required=False,
        help_text="Includes connector status in the status payload. Disable for better performance",
    )
    alert_agent_of_automated_message_sent = forms.BooleanField(
        required=False,
        help_text="Alert the agent whenever you send an automated text."
        + "WARNING: this option will cause a bot to react to those messages.",
    )
    auto_answer_incoming_call = forms.CharField(
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Auto answer this message on incoming call",
        required=False,
    )
    convert_incoming_call_to_text = forms.CharField(
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Convert an Incoming Call to this text (can be used to force a bot reaction)",
        required=False,
    )
    auto_answer_on_audio_message = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Auto answer with this message when a user end audio (PTT)",
    )
    convert_incoming_audio_to_text = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Convert a user audio to this message (can be used to force a bot reaction)",
    )
    welcome_message = forms.CharField(
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Auto answer this message as Welcome Message",
        required=False,
    )
    welcome_vcard = forms.JSONField(
        required=False, initial={}, help_text="The Payload for a Welcome Vcard"
    )
    session_taken_alert_template = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Template to use for the alert session taken. eg. \
        You are now talking with {{agent.name}} at department {{department.name}}",
    )
    session_taken_alert_ignore_departments = forms.CharField(
        required=False,
        help_text="Ignore this departments ID for the session taken alert."
        + "multiple separated with comma. eg. departmentID1,departmentID2",
    )
    no_agent_online_alert_admin = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="""Template to alert admin when no agent is online.
        Eg: No agent online!. **Message**: {{body}} **From**: {{from}}""",
    )
    no_agent_online_autoanswer_visitor = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 4, "cols": 15}),
        help_text="Template to auto answer visitor when no agent is online",
    )
class AdvSearchPageForm(forms.Form):
    """
    Advanced search download form for any advanced search data.
    """

    ROWS_PER_PAGE_CHOICES = (
        ("10", "10"),
        ("25", "25"),
        ("50", "50"),
        ("100", "100"),
        ("200", "200"),
        ("500", "500"),
        ("1000", "1000"),
    )

    qryjson = forms.JSONField(widget=forms.HiddenInput())
    rows = forms.ChoiceField(
        choices=ROWS_PER_PAGE_CHOICES,
        widget=RowsPerPageSelectWidget(),
    )
    page = forms.CharField(widget=forms.HiddenInput())
    order_by = forms.CharField(widget=forms.HiddenInput())
    order_direction = forms.CharField(widget=forms.HiddenInput())
    paging = forms.CharField(
        widget=forms.HiddenInput()
    )  # This field's name ("paging") is used to distinguish pager form submissions from other form submissions
    show_stats = forms.BooleanField(widget=forms.HiddenInput())
    stats = forms.JSONField(widget=forms.HiddenInput())

    def clean(self):
        """
        This override of super.clean is so we can reconstruct the search inputs upon form_invalid in views.py
        """
        self.saved_data = self.cleaned_data
        return self.cleaned_data

    def update(
        self, page_id, rows_id, orderby_id, orderdir_id, rows_attrs={}, other_ids=None
    ):
        """
        Adds IDs and other attributes to form elements.
        """
        # Allow IDs for the inputs to be set for javascript to find the inputs and change them
        page = self.fields.get("page")
        rows = self.fields.get("rows")
        order_by = self.fields.get("order_by")
        order_direction = self.fields.get("order_direction")

        #
        # Make sure any future hard-coded settings are not silently over-ridden
        #

        # page input
        if (
            page.widget.attrs
            and "id" in page.widget.attrs
            and page.widget.attrs["id"] != page_id
        ):
            raise Exception(
                "ERROR: AdvSearchPageForm class already has an ID set for the page input"
            )
        page.widget.attrs["id"] = page_id

        # rows input
        if (
            rows.widget.attrs
            and "id" in rows.widget.attrs
            and rows.widget.attrs["id"] != rows_id
        ):
            raise Exception(
                "ERROR: AdvSearchPageForm class already has an ID set for the rows input"
            )
        rows.widget.attrs["id"] = rows_id

        # order_by input
        if (
            order_by.widget.attrs
            and "id" in order_by.widget.attrs
            and order_by.widget.attrs["id"] != orderby_id
        ):
            raise Exception(
                "ERROR: AdvSearchPageForm class already has an ID set for the order_by input"
            )
        order_by.widget.attrs["id"] = orderby_id

        # order_direction input
        if (
            order_direction.widget.attrs
            and "id" in order_direction.widget.attrs
            and order_direction.widget.attrs["id"] != orderdir_id
        ):
            raise Exception(
                "ERROR: AdvSearchPageForm class already has an ID set for the order_direction input"
            )
        order_direction.widget.attrs["id"] = orderdir_id

        # Allow setting of additional attributes for appearance of the rows select list. Others are assumed to be
        # hidden and page control is assumed to be accomplished using submit buttons that run javascript
        for key, val in rows_attrs.items():
            if (
                rows.widget.attrs
                and key in rows.widget.attrs
                and rows.widget.attrs[key] != val
            ):
                raise Exception(
                    "ERROR: AdvSearchPageForm class already has a [{key}] set for the rows input"
                )
            rows.widget.attrs[key] = val

        if other_ids is not None:
            for fld_name in other_ids.keys():
                fld = self.fields.get(fld_name)
                if (
                    fld.widget.attrs
                    and "id" in fld.widget.attrs
                    and fld.widget.attrs["id"] != other_ids[fld_name]
                ):
                    raise Exception(
                        f"ERROR: AdvSearchPageForm class already has an ID set for the {fld_name} input"
                    )
                fld.widget.attrs["id"] = other_ids[fld_name]

    def is_valid(self):
        # This triggers the setting of self.cleaned_data
        super().is_valid()
        data = self.cleaned_data
        fields = self.base_fields.keys()
        ignore_missing_fields = [
            "order_by",
            "order_direction",
            "show_stats",
            "stats",
        ]
        # Make sure all fields besides the order fields are present
        for field in fields:
            if field not in ignore_missing_fields and field not in data:
                return False
        return True
Esempio n. 19
0
class AddProductForm(forms.Form):
    product_id = forms.IntegerField(min_value=0)
    selected_color_id = forms.IntegerField(min_value=0, required=False)
    selected_options = forms.JSONField(required=False)

    def clean_product_id(self):
        product_id = self.cleaned_data['product_id']
        product_query = Product.objects.filter(id=product_id)
        if not product_query.exists():
            raise ValidationError(
                f"Product with id={product_id} doesnt exists")

        self.cleaned_data['product'] = product_query.first()
        return product_id

    def clean_selected_options(self):
        selected_options = self.cleaned_data['selected_options']
        if not isinstance(selected_options, dict):
            raise ValidationError("Selected options should be a dictionary")
        return selected_options

    def clean(self):
        cleaned_data = super().clean()
        product = self.cleaned_data['product']

        # parsing color
        if "selected_color_id" in self.cleaned_data and self.cleaned_data[
                'selected_color_id']:
            selected_color_id = self.cleaned_data['selected_color_id']

            selected_color_query = product. \
                all_raw_colors. \
                filter(id=selected_color_id)

            if not selected_color_query.exists():
                raise ValidationError(
                    f"Color with id={selected_color_id} at product "
                    f"with id={product.id} doesnt exists")

            selected_color = selected_color_query.first()
            cleaned_data['selected_color'] = selected_color
        else:
            if product.all_colors.count() != 0:
                raise ValidationError(
                    f"no selected_color_id, but product has colors")
            else:
                cleaned_data['selected_color'] = None

        # parsing selected options
        if 'selected_options' in self.cleaned_data:
            selected_options_json = self.cleaned_data['selected_options']
            selected_options = list()
            for options_title, option_id in selected_options_json.items():
                options_query = product.all_options.filter(title=options_title)
                if not options_query.exists():
                    raise ValidationError(
                        f"Product options with title={options_title} at product "
                        f"with id={product.id} doesnt exists")

                product_options = options_query.get()
                option_query = product_options.options.filter(id=option_id)
                if not option_query.exists():
                    raise ValidationError(
                        f"Product option with id={option_id} "
                        f"at product_options with id={product_options.id} "
                        f"doesnt exists")

                option = option_query.get()
                selected_options.append(
                    SelectedProductOption.create_from_option(
                        options_obj=product_options,
                        option=option,
                    ))

            cleaned_data['selected_options'] = selected_options
        else:
            cleaned_data['selected_options'] = []
Esempio n. 20
0
class LiftingForm(forms.ModelForm):
    lift_data = forms.JSONField()

    class Meta:
        model = Lifting
        exclude = ('ath_user', 'lift_date')
Esempio n. 21
0
class ThrowingForm(forms.ModelForm):
    throw_data = forms.JSONField()

    class Meta:
        model = Throwing
        exclude = ('ath_user', 'throw_date')
Esempio n. 22
0
class RecordListFilterForm(forms.Form):
    filters = forms.JSONField(required=False, empty_value=[])
    order_by = forms.JSONField(required=False, empty_value=[])
    group_count_by = forms.JSONField(required=False, empty_value=[])
Esempio n. 23
0
    def to_form_field(self,
                      set_initial=True,
                      enforce_required=True,
                      for_csv_import=False):
        """
        Return a form field suitable for setting a CustomField's value for an object.

        set_initial: Set initial data for the field. This should be False when generating a field for bulk editing.
        enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
        for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
        """
        initial = self.default if set_initial else None
        required = self.required if enforce_required else False

        # Integer
        if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
            field = forms.IntegerField(required=required,
                                       initial=initial,
                                       min_value=self.validation_minimum,
                                       max_value=self.validation_maximum)

        # Boolean
        elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
            choices = (
                (None, '---------'),
                (True, 'True'),
                (False, 'False'),
            )
            field = forms.NullBooleanField(
                required=required,
                initial=initial,
                widget=StaticSelect(choices=choices))

        # Date
        elif self.type == CustomFieldTypeChoices.TYPE_DATE:
            field = forms.DateField(required=required,
                                    initial=initial,
                                    widget=DatePicker())

        # Select
        elif self.type in (CustomFieldTypeChoices.TYPE_SELECT,
                           CustomFieldTypeChoices.TYPE_MULTISELECT):
            choices = [(c, c) for c in self.choices]
            default_choice = self.default if self.default in self.choices else None

            if not required or default_choice is None:
                choices = add_blank_choice(choices)

            # Set the initial value to the first available choice (if any)
            if set_initial and default_choice:
                initial = default_choice

            if self.type == CustomFieldTypeChoices.TYPE_SELECT:
                field_class = CSVChoiceField if for_csv_import else forms.ChoiceField
                field = field_class(choices=choices,
                                    required=required,
                                    initial=initial,
                                    widget=StaticSelect())
            else:
                field_class = CSVMultipleChoiceField if for_csv_import else forms.MultipleChoiceField
                field = field_class(choices=choices,
                                    required=required,
                                    initial=initial,
                                    widget=StaticSelectMultiple())

        # URL
        elif self.type == CustomFieldTypeChoices.TYPE_URL:
            field = LaxURLField(required=required, initial=initial)

        # JSON
        elif self.type == CustomFieldTypeChoices.TYPE_JSON:
            field = forms.JSONField(required=required, initial=initial)

        # Text
        else:
            if self.type == CustomFieldTypeChoices.TYPE_LONGTEXT:
                max_length = None
                widget = forms.Textarea
            else:
                max_length = 255
                widget = None
            field = forms.CharField(max_length=max_length,
                                    required=required,
                                    initial=initial,
                                    widget=widget)
            if self.validation_regex:
                field.validators = [
                    RegexValidator(
                        regex=self.validation_regex,
                        message=mark_safe(
                            f"Values must match this regex: <code>{self.validation_regex}</code>"
                        ))
                ]

        field.model = self
        field.label = str(self)
        if self.description:
            field.help_text = escape(self.description)

        return field
Esempio n. 24
0
class ExampleForm(forms.Form):
    """Demonstration of all Django form fields / widgets"""

    boolean_required = forms.BooleanField(
        help_text="boolean required field’s help text")
    boolean_optional = forms.BooleanField(
        help_text="boolean optional field’s help text", required=False)
    boolean_disabled = forms.BooleanField(
        help_text="boolean disabled field’s help text", disabled=True)

    char_required = forms.CharField(
        help_text="char required field’s help text", required=True)
    char_optional = forms.CharField(
        help_text="char optional field’s help text", required=False)
    char_disabled = forms.CharField(
        help_text="char disabled field’s help text", disabled=True)

    password_required = forms.CharField(help_text="field’s help text",
                                        required=True,
                                        widget=forms.PasswordInput())
    password_optional = forms.CharField(help_text="field’s help text",
                                        required=False,
                                        widget=forms.PasswordInput())
    password_disabled = forms.CharField(help_text="field’s help text",
                                        disabled=True,
                                        widget=forms.PasswordInput())

    char_hidden = forms.CharField(widget=forms.HiddenInput())

    multiline_required = forms.CharField(
        widget=forms.Textarea(attrs={
            "rows": 10,
            "cols": 40
        }),
        help_text="field’s help text",
        required=True,
    )
    multiline_optional = forms.CharField(
        widget=forms.Textarea(attrs={
            "rows": 10,
            "cols": 40
        }),
        help_text="field’s help text",
        required=False,
    )
    multiline_disabled = forms.CharField(
        widget=forms.Textarea(attrs={
            "rows": 10,
            "cols": 40
        }),
        help_text="field’s help text",
        required=False,
    )

    choices = (("one", "One"), ("two", "Two"), ("three", "Three"), ("four",
                                                                    "Four"))

    choice_required = forms.ChoiceField(help_text="field’s help text",
                                        choices=choices,
                                        required=True)
    choice_optional = forms.ChoiceField(help_text="field’s help text",
                                        choices=choices,
                                        required=False)
    choice_disabled = forms.ChoiceField(help_text="field’s help text",
                                        choices=choices,
                                        disabled=True)

    radio_choice_required = forms.ChoiceField(help_text="field’s help text",
                                              choices=choices,
                                              required=True,
                                              widget=forms.RadioSelect())
    radio_choice_optional = forms.ChoiceField(help_text="field’s help text",
                                              choices=choices,
                                              required=False,
                                              widget=forms.RadioSelect())
    radio_choice_disabled = forms.ChoiceField(help_text="field’s help text",
                                              choices=choices,
                                              disabled=True,
                                              widget=forms.RadioSelect())

    date_required = forms.DateField(
        help_text="date required field’s help text", required=True)
    date_optional = forms.DateField(
        help_text="date optional field’s help text", required=False)
    date_disabled = forms.DateField(
        help_text="date disabled field’s help text", disabled=True)

    datetime_required = forms.DateTimeField(
        help_text="datetime required field’s help text", required=True)
    datetime_optional = forms.DateTimeField(
        help_text="datetime optional field’s help text", required=False)
    datetime_disabled = forms.DateTimeField(
        help_text="datetime disabled field’s help text", disabled=True)

    decimal_required = forms.DecimalField(
        help_text="decimal required field’s help text", required=True)
    decimal_optional = forms.DecimalField(
        help_text="decimal optional field’s help text", required=False)
    decimal_disabled = forms.DecimalField(
        help_text="decimal disabled field’s help text", disabled=True)

    duration_required = forms.DurationField(
        help_text="duration required field’s help text", required=True)
    duration_optional = forms.DurationField(
        help_text="duration optional field’s help text", required=False)
    duration_disabled = forms.DurationField(
        help_text="duration disabled field’s help text", disabled=True)

    email_required = forms.EmailField(
        help_text="email required field’s help text", required=True)
    email_optional = forms.EmailField(
        help_text="email optional field’s help text", required=False)
    email_disabled = forms.EmailField(
        help_text="email disabled field’s help text", disabled=True)

    file_required = forms.FileField(
        help_text="file required field’s help text", required=True)
    file_optional = forms.FileField(
        help_text="file optional field’s help text", required=False)
    file_disabled = forms.FileField(
        help_text="file disabled field’s help text", disabled=True)

    # FilePathField

    float_required = forms.FloatField(
        help_text="float required field’s help text", required=True)
    float_optional = forms.FloatField(
        help_text="float optional field’s help text", required=False)
    float_disabled = forms.FloatField(
        help_text="float disabled field’s help text", disabled=True)

    image_required = forms.ImageField(
        help_text="image required field’s help text", required=True)
    image_optional = forms.ImageField(
        help_text="image optional field’s help text", required=False)
    image_disabled = forms.ImageField(
        help_text="image disabled field’s help text", disabled=True)

    integer_required = forms.IntegerField(
        help_text="integer required field’s help text", required=True)
    integer_optional = forms.IntegerField(
        help_text="integer optional field’s help text", required=False)
    integer_disabled = forms.IntegerField(
        help_text="integer disabled field’s help text", disabled=True)

    json_required = forms.JSONField(
        label="JSON required",
        help_text="json required field’s help text",
        required=True)
    json_optional = forms.JSONField(
        label="JSON optional",
        help_text="json optional field’s help text",
        required=False)
    json_disabled = forms.JSONField(
        label="JSON disabled",
        help_text="json disabled field’s help text",
        disabled=True)

    generic_ip_address_required = forms.GenericIPAddressField(
        help_text="generic ip address required field’s help text",
        required=True)
    generic_ip_address_optional = forms.GenericIPAddressField(
        help_text="generic ip address optional field’s help text",
        required=False)
    generic_ip_address_disabled = forms.GenericIPAddressField(
        help_text="generic ip address disabled field’s help text",
        disabled=True)

    select_multiple = forms.MultipleChoiceField(choices=choices)
    checkboxes_multiple = forms.MultipleChoiceField(
        choices=choices, widget=forms.CheckboxSelectMultiple())

    # TypedMultipleChoiceField

    null_boolean_required = forms.NullBooleanField(
        help_text="null boolean required field’s help text")
    null_boolean_optional = forms.NullBooleanField(
        help_text="null boolean optional field’s help text", required=False)
    null_boolean_disabled = forms.NullBooleanField(
        help_text="null boolean disabled field’s help text", disabled=True)

    # SlugField

    regex_required = forms.RegexField(
        regex="\w",
        help_text="regex required field’s help text",
        required=True)
    regex_optional = forms.RegexField(
        regex="\w",
        help_text="regex optional field’s help text",
        required=False)
    regex_disabled = forms.RegexField(
        regex="\w",
        help_text="regex disabled field’s help text",
        disabled=True)

    slug_required = forms.SlugField(
        help_text="slug required field’s help text", required=True)
    slug_optional = forms.SlugField(
        help_text="slug optional field’s help text", required=False)
    slug_disabled = forms.SlugField(
        help_text="slug disabled field’s help text", disabled=True)

    time_required = forms.TimeField(
        help_text="time required field’s help text", required=True)
    time_optional = forms.TimeField(
        help_text="time optional field’s help text", required=False)
    time_disabled = forms.TimeField(
        help_text="time disabled field’s help text", disabled=True)

    url_required = forms.URLField(label="URL required",
                                  help_text="url required field’s help text",
                                  required=True)
    url_optional = forms.URLField(label="URL optional",
                                  help_text="url optional field’s help text",
                                  required=False)
    url_disabled = forms.URLField(label="URL disabled",
                                  help_text="url disabled field’s help text",
                                  disabled=True)

    uuid_required = forms.UUIDField(
        label="UUID required",
        help_text="uuid required field’s help text",
        required=True)
    uuid_optional = forms.UUIDField(
        label="UUID optional",
        help_text="uuid optional field’s help text",
        required=False)
    uuid_disabled = forms.UUIDField(
        label="UUID disabled",
        help_text="uuid disabled field’s help text",
        disabled=True)

    combo_required = forms.ComboField(
        fields=[forms.CharField(max_length=20),
                forms.EmailField()],
        help_text="combo required field’s help text",
        required=True)
    combo_optional = forms.ComboField(
        fields=[forms.CharField(max_length=20),
                forms.EmailField()],
        help_text="combo optional field’s help text",
        required=False)
    combo_disabled = forms.ComboField(
        fields=[forms.CharField(max_length=20),
                forms.EmailField()],
        help_text="combo disabled field’s help text",
        disabled=True)