コード例 #1
0
ファイル: forms.py プロジェクト: guoyu07/sentry-jira
class JIRAIssueForm(forms.Form):

    project_key = forms.CharField(widget=forms.HiddenInput())
    project = forms.CharField(widget=forms.HiddenInput())
    issuetype = forms.ChoiceField(
        label="Issue Type",
        help_text=
        "Changing the issue type will refresh the page with the required form fields.",
        required=True)

    summary = forms.CharField(label=_("Issue Summary"),
                              widget=forms.TextInput(attrs={'class': 'span6'}))
    description = forms.CharField(widget=forms.Textarea(
        attrs={"class": 'span6'}))

    def __init__(self, *args, **kwargs):
        self.ignored_fields = kwargs.pop("ignored_fields")
        initial = kwargs.get("initial")
        jira_client = initial.pop("jira_client")

        priorities = jira_client.get_priorities().json
        versions = jira_client.get_versions(initial.get("project_key")).json

        # Returns the metadata the configured JIRA instance requires for
        # creating issues for a given project.
        # https://developer.atlassian.com/static/rest/jira/5.0.html#id200251
        meta = jira_client.get_create_meta(initial.get("project_key")).json

        # Early exit, somehow made it here without properly configuring the
        # plugin.
        if not meta or not priorities:
            super(JIRAIssueForm, self).__init__(*args, **kwargs)
            self.errors["__all__"] = [
                "Error communicating with JIRA, Please check your configuration."
            ]
            return

        # Early exit #2, no projects available.
        if len(meta["projects"]) is 0:
            super(JIRAIssueForm, self).__init__(*args, **kwargs)
            self.errors["__all__"] = [
                "Error in JIRA configuration, no projects found for user %s." %
                jira_client.username
            ]
            return

        # Looking up the project meta by exact key, so it's always the first
        # one.
        project = meta["projects"][0]
        issue_types = project["issuetypes"]

        # check if the issuetype was passed as a GET parameter
        self.issue_type = initial.get("issuetype")
        if self.issue_type:
            matching_type = [
                t for t in issue_types if t["id"] == self.issue_type
            ]
            self.issue_type = matching_type[0] if len(
                matching_type) > 0 else None

        # still no issue type? just use the first one.
        if not self.issue_type:
            self.issue_type = issue_types[0]

        # set back after we've played with the inital data
        kwargs["initial"] = initial

        # call the super to bind self.fields from the defaults.
        super(JIRAIssueForm, self).__init__(*args, **kwargs)

        self.fields["project"].initial = project["id"]
        self.fields["issuetype"].choices = self.make_choices(issue_types)

        # apply ordering to fields based on some known built-in JIRA fields.
        # otherwise weird ordering occurs.
        anti_gravity = {
            "priority": -150,
            "fixVersions": -125,
            "components": -100,
            "security": -50
        }

        dynamic_fields = self.issue_type.get("fields").keys()
        dynamic_fields.sort(key=lambda f: anti_gravity.get(f) or 0)
        # build up some dynamic fields based on required shit.
        for field in dynamic_fields:
            if field in self.fields.keys() or field in [
                    x.strip() for x in self.ignored_fields.split(",")
            ]:
                # don't overwrite the fixed fields for the form.
                continue
            mb_field = self.build_dynamic_field(
                self.issue_type["fields"][field])
            if mb_field:
                # apply field to form
                self.fields[field] = mb_field

        if "priority" in self.fields.keys():
            # whenever priorities are available, put the available ones in the list.
            # allowedValues for some reason doesn't pass enough info.
            self.fields["priority"].choices = self.make_choices(priorities)

        if "fixVersions" in self.fields.keys():
            self.fields["fixVersions"].choices = self.make_choices(versions)

    make_choices = lambda self, x: [(y["id"], y["name"]
                                     if "name" in y else y["value"])
                                    for y in x] if x else []

    def clean_description(self):
        """
        Turn code blocks that are in the stack trace into JIRA code blocks.
        """
        desc = self.cleaned_data["description"]
        return desc.replace("```", "{code}")

    def clean(self):
        """
        The form clean method needs to take advantage of the loaded issue type
        fields and meta info so it can determine the format that the datatypes
        should render as.
        """
        very_clean = self.cleaned_data

        # protect against mis-configured plugin submitting a form without an
        # issuetype assigned.
        if not very_clean.get("issuetype"):
            raise ValidationError(
                "Issue Type is required. Check your plugin configuration.")

        fs = self.issue_type["fields"]
        for field in fs.keys():
            f = fs[field]
            if field in ["description", "summary"]:
                continue
            if field in very_clean.keys():
                v = very_clean.get(field)
                if v:
                    schema = f["schema"]
                    if schema.get("type") == "string" and not schema.get(
                            "custom") == CUSTOM_FIELD_TYPES["select"]:
                        continue  # noop
                    if schema.get("type") == "date":
                        continue
                    if schema["type"] == "user" or schema.get(
                            'item') == "user":
                        v = {"name": v}
                    elif schema.get("custom") == CUSTOM_FIELD_TYPES.get(
                            "multiuserpicker"):
                        # custom multi-picker
                        v = [{"name": v}]
                    elif schema["type"] == "array" and schema.get(
                            "item") != "string":
                        v = [{"id": vx} for vx in v]
                    elif schema.get("custom") == CUSTOM_FIELD_TYPES.get(
                            "textarea"):
                        v = v
                    elif (schema.get("type") != "string"
                          or schema.get("item") != "string"
                          or schema.get("custom")
                          == CUSTOM_FIELD_TYPES.get("select")):
                        v = {"id": v}
                    very_clean[field] = v
                else:
                    # We don't want to pass blank data back to the API, so kill
                    # None values
                    very_clean.pop(field, None)

        if not (isinstance(very_clean["issuetype"], dict)
                and "id" in very_clean["issuetype"]):
            # something fishy is going on with this field, working on some JIRA
            # instances, and some not.
            # testing against 5.1.5 and 5.1.4 does not convert (perhaps is no longer included
            # in the projectmeta API call, and would normally be converted in the
            # above clean method.)
            very_clean["issuetype"] = {"id": very_clean["issuetype"]}

        very_clean.pop("project_key", None)

        return very_clean

    def build_dynamic_field(self, field_meta):
        """
        Builds a field based on JIRA's meta field information
        """
        schema = field_meta["schema"]
        # set up some defaults for form fields
        fieldtype = forms.CharField
        fkwargs = {
            'label': field_meta["name"],
            'required': field_meta["required"],
            'widget': forms.TextInput(attrs={'class': 'span6'})
        }

        # override defaults based on field configuration
        if (schema["type"] in ["securitylevel", "priority"]
                or schema.get("custom") == CUSTOM_FIELD_TYPES.get("select")):
            fieldtype = forms.ChoiceField
            fkwargs["choices"] = self.make_choices(
                field_meta.get('allowedValues'))
            fkwargs["widget"] = forms.Select()
        elif schema.get("items") == "user" or schema["type"] == "user":
            fkwargs["widget"] = forms.TextInput(
                attrs={
                    'class': 'user-selector',
                    'data-autocomplete': field_meta.get("autoCompleteUrl")
                })
        elif schema["type"] in ["timetracking"]:
            # TODO: Implement timetracking (currently unsupported alltogether)
            return None
        elif schema.get("items") in ["worklog", "attachment"]:
            # TODO: Implement worklogs and attachments someday
            return None
        elif schema["type"] == "array" and schema["items"] != "string":
            fieldtype = forms.MultipleChoiceField
            fkwargs["choices"] = self.make_choices(
                field_meta.get("allowedValues"))
            fkwargs["widget"] = forms.SelectMultiple()

        # break this out, since multiple field types could additionally
        # be configured to use a custom property instead of a default.
        if schema.get("custom"):
            if schema["custom"] == CUSTOM_FIELD_TYPES.get("textarea"):
                fkwargs["widget"] = forms.Textarea(attrs={'class': 'span6'})

        return fieldtype(**fkwargs)
コード例 #2
0
ファイル: forms.py プロジェクト: katherinsb/test
class Contacto(forms.Form):
	nombre = forms.CharField(max_length=100, widget=forms.TextInput(attrs={ 'class': 'name', 'placeholder': 'Nombre'})) 
	correo = forms.CharField(max_length=100, widget=forms.TextInput(attrs={ 'class': 'email', 'placeholder': 'Correo'}))
	numero = forms.CharField(max_length=100, widget=forms.TextInput(attrs={ 'class': 'phone', 'placeholder': 'Telefono'}))
	texto = forms.CharField( widget=forms.Textarea(attrs={ 'class': 'message', 'cols': '30', 'rows': '10', 'placeholder':'Mensaje', 'id': 'message'}))
	archivo = forms.FileField(widget=forms.FileInput(attrs={'class': 'file'}))
コード例 #3
0
ファイル: produto.py プロジェクト: qdwxfnh/DjangoSIGE
 class Meta:
     model = Produto
     fields = (
         'codigo',
         'codigo_barras',
         'descricao',
         'categoria',
         'marca',
         'unidade',
         'ncm',
         'venda',
         'custo',
         'inf_adicionais',
         'origem',
         'cest',
         'cfop_padrao',
         'grupo_fiscal',
         'estoque_minimo',
         'controlar_estoque',
     )
     widgets = {
         'codigo':
         forms.TextInput(attrs={'class': 'form-control'}),
         'codigo_barras':
         forms.TextInput(attrs={'class': 'form-control'}),
         'descricao':
         forms.TextInput(attrs={'class': 'form-control'}),
         'categoria':
         forms.Select(attrs={'class': 'form-control'}),
         'marca':
         forms.Select(attrs={'class': 'form-control'}),
         'unidade':
         forms.Select(attrs={'class': 'form-control'}),
         'ncm':
         forms.TextInput(attrs={'class': 'form-control'}),
         'inf_adicionais':
         forms.Textarea(attrs={'class': 'form-control'}),
         'origem':
         forms.Select(attrs={'class': 'form-control'}),
         'cest':
         forms.TextInput(attrs={'class': 'form-control'}),
         'cfop_padrao':
         forms.Select(attrs={'class': 'form-control'}),
         'grupo_fiscal':
         forms.Select(attrs={'class': 'form-control'}),
         'estoque_minimo':
         forms.TextInput(attrs={'class': 'form-control decimal-mask'}),
         'controlar_estoque':
         forms.CheckboxInput(attrs={'class': 'form-control'}),
     }
     labels = {
         'codigo': _('代码'),
         'codigo_barras': _('条码(GTIN/EAN)'),
         'descricao': _('说明'),
         'categoria': _('分类'),
         'marca': _('品牌'),
         'unidade': _('单位'),
         'ncm': _('NCM'),
         'inf_adicionais': _('备注'),
         'origem': _('产地'),
         'cest': _('CEST'),
         'cfop_padrao': _('CFOP(标准)'),
         'grupo_fiscal': _('税务组(模式)'),
         'estoque_minimo': _('Qtd最低限度'),
         'controlar_estoque': _('是否控制这个产品的库存?'),
     }
コード例 #4
0
ファイル: forms.py プロジェクト: KAOXDC/2067960
class contacto_form (forms.Form):
	correo = forms.EmailField(widget = forms.TextInput())
	titulo = forms.CharField(widget = forms.TextInput())
	texto  = forms.CharField(widget = forms.Textarea())
コード例 #5
0
ファイル: forms.py プロジェクト: Zmora-GH/django-tmp-project
 class Meta:
     prefix = 'task_form'
     model = Task
     fields = ['title', 'body', 'stage', 'bg']
     widgets = {'body': forms.Textarea()}
コード例 #6
0
ファイル: forms.py プロジェクト: andrewhayward/gameon
from django.forms.models import ModelChoiceField

from gameon.submissions.widgets import CategorySelectWidget

from gameon.submissions.models import Entry, Category

MARKET_CHOICES = (('True', 'Yes, I want to submit by game to the marketplace (you will get forwarded to the Firefox Marketplace on submission)'),
    ('False', "No, I don't want to submit my game to the marketplace"))

entry_fields = ('title', 'url', 'description', 'category', 'thumbnail',
            'video_url', 'team_name', 'team_members', 'team_description',
            'to_market')

entry_widgets = {
    'url': forms.TextInput(attrs={'aria-describedby': 'info_url'}),
    'description': forms.Textarea(attrs={'aria-describedby': 'info_description',
        'data-maxlength': '1000'}),
    'video_url': forms.TextInput(attrs={'aria-describedby': 'info_video_url'}),
    'team_members': forms.Textarea(attrs={'aria-describedby': 'info_team_members',
        'data-maxlength': '250'}),
    'team_description': forms.Textarea(attrs={'aria-describedby': 'info_team_description',
        'data-maxlength': '250'}),
    'to_market': forms.RadioSelect(choices=MARKET_CHOICES),
}


class EntryForm(forms.ModelForm):

    category = ModelChoiceField(queryset=Category.objects.all(),
                                empty_label=None,
                                widget=CategorySelectWidget())
コード例 #7
0
class CreateRearrangement(forms.Form):
    new_date_time = forms.DateTimeField(
        widget=forms.DateInput(attrs={'id': 'datepicker'}), label="New date")
    reason = forms.CharField(max_length=200, widget=forms.Textarea())
コード例 #8
0
ファイル: orders.py プロジェクト: ashudwi/pretix
class EventCancelForm(forms.Form):
    subevent = forms.ModelChoiceField(SubEvent.objects.none(),
                                      label=pgettext_lazy('subevent', 'Date'),
                                      required=False,
                                      empty_label=pgettext_lazy(
                                          'subevent', 'All dates'))
    all_subevents = forms.BooleanField(label=_('Cancel all dates'),
                                       initial=False,
                                       required=False)
    auto_refund = forms.BooleanField(
        label=_('Automatically refund money if possible'),
        initial=True,
        required=False)
    manual_refund = forms.BooleanField(
        label=
        _('Create manual refund if the payment method odes not support automatic refunds'
          ),
        widget=forms.CheckboxInput(
            attrs={'data-display-dependency': '#id_auto_refund'}),
        initial=True,
        required=False,
        help_text=
        _('If checked, all payments with a payment method not supporting automatic refunds will be on your '
          'manual refund to-do list. Do not check if you want to refund some of the orders by offsetting '
          'with different orders or issuing gift cards.'))
    refund_as_giftcard = forms.BooleanField(
        label=
        _('Refund order value to a gift card instead instead of the original payment method'
          ),
        widget=forms.CheckboxInput(
            attrs={'data-display-dependency': '#id_auto_refund'}),
        initial=False,
        required=False,
    )
    gift_card_expires = SplitDateTimeField(
        label=_('Gift card validity'),
        required=False,
        widget=SplitDateTimePickerWidget(
            attrs={'data-display-dependency': '#id_refund_as_giftcard'}, ))
    gift_card_conditions = forms.CharField(
        label=_('Special terms and conditions'),
        required=False,
        widget=forms.Textarea(attrs={
            'rows':
            2,
            'data-display-dependency':
            '#id_refund_as_giftcard'
        }, ))
    keep_fee_fixed = forms.DecimalField(
        label=_("Keep a fixed cancellation fee"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fee_percentage = forms.DecimalField(
        label=_("Keep a percentual cancellation fee"),
        max_digits=10,
        decimal_places=2,
        required=False)
    keep_fees = forms.MultipleChoiceField(
        label=_("Keep fees"),
        widget=forms.CheckboxSelectMultiple,
        choices=[(k, v) for k, v in OrderFee.FEE_TYPES
                 if k != OrderFee.FEE_TYPE_GIFTCARD],
        help_text=
        _('The selected types of fees will not be refunded but instead added to the cancellation fee. Fees '
          'are never refunded in when an order in an event series is only partially canceled since it '
          'consists of tickets for multiple dates.'),
        required=False,
    )
    send = forms.BooleanField(label=_("Send information via email"),
                              required=False)
    send_subject = forms.CharField()
    send_message = forms.CharField()
    send_waitinglist = forms.BooleanField(
        label=_("Send information to waiting list"), required=False)
    send_waitinglist_subject = forms.CharField()
    send_waitinglist_message = forms.CharField()

    def _set_field_placeholders(self, fn, base_parameters):
        phs = [
            '{%s}' % p for p in sorted(
                get_available_placeholders(self.event, base_parameters).keys())
        ]
        ht = _('Available placeholders: {list}').format(list=', '.join(phs))
        if self.fields[fn].help_text:
            self.fields[fn].help_text += ' ' + str(ht)
        else:
            self.fields[fn].help_text = ht
        self.fields[fn].validators.append(PlaceholderValidator(phs))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        kwargs.setdefault('initial', {})
        kwargs['initial'][
            'gift_card_expires'] = self.event.organizer.default_gift_card_expiry
        super().__init__(*args, **kwargs)
        self.fields['send_subject'] = I18nFormField(
            label=_("Subject"),
            required=True,
            widget_kwargs={'attrs': {
                'data-display-dependency': '#id_send'
            }},
            initial=_('Canceled: {event}'),
            widget=I18nTextInput,
            locales=self.event.settings.get('locales'),
        )
        self.fields['send_message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            widget_kwargs={'attrs': {
                'data-display-dependency': '#id_send'
            }},
            locales=self.event.settings.get('locales'),
            initial=LazyI18nString.from_gettext(
                gettext_noop(
                    'Hello,\n\n'
                    'with this email, we regret to inform you that {event} has been canceled.\n\n'
                    'We will refund you {refund_amount} to your original payment method.\n\n'
                    'You can view the current state of your order here:\n\n{url}\n\nBest regards,\n\n'
                    'Your {event} team')))

        self._set_field_placeholders('send_subject', [
            'event_or_subevent', 'refund_amount', 'position_or_address',
            'order', 'event'
        ])
        self._set_field_placeholders('send_message', [
            'event_or_subevent', 'refund_amount', 'position_or_address',
            'order', 'event'
        ])
        self.fields['send_waitinglist_subject'] = I18nFormField(
            label=_("Subject"),
            required=True,
            initial=_('Canceled: {event}'),
            widget=I18nTextInput,
            widget_kwargs={
                'attrs': {
                    'data-display-dependency': '#id_send_waitinglist'
                }
            },
            locales=self.event.settings.get('locales'),
        )
        self.fields['send_waitinglist_message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            locales=self.event.settings.get('locales'),
            widget_kwargs={
                'attrs': {
                    'data-display-dependency': '#id_send_waitinglist'
                }
            },
            initial=LazyI18nString.from_gettext(
                gettext_noop(
                    'Hello,\n\n'
                    'with this email, we regret to inform you that {event} has been canceled.\n\n'
                    'You will therefore not receive a ticket from the waiting list.\n\n'
                    'Best regards,\n\n'
                    'Your {event} team')))
        self._set_field_placeholders('send_waitinglist_subject',
                                     ['event_or_subevent', 'event'])
        self._set_field_placeholders('send_waitinglist_message',
                                     ['event_or_subevent', 'event'])

        if self.event.has_subevents:
            self.fields['subevent'].queryset = self.event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2':
                    'event',
                    'data-select2-url':
                    reverse('control:event.subevents.select2',
                            kwargs={
                                'event': self.event.slug,
                                'organizer': self.event.organizer.slug,
                            }),
                    'data-placeholder':
                    pgettext_lazy('subevent', 'All dates')
                })
            self.fields['subevent'].widget.choices = self.fields[
                'subevent'].choices
        else:
            del self.fields['subevent']
            del self.fields['all_subevents']
        change_decimal_field(self.fields['keep_fee_fixed'],
                             self.event.currency)

    def clean(self):
        d = super().clean()
        if self.event.has_subevents and not d['subevent'] and not d[
                'all_subevents']:
            raise ValidationError(
                _('Please confirm that you want to cancel ALL dates in this event series.'
                  ))
        return d
コード例 #9
0
ファイル: forms.py プロジェクト: siolag161/tendenci
class CorpMembershipAppForm(TendenciBaseForm):
    description = forms.CharField(
        required=False,
        widget=TinyMCE(attrs={'style': 'width:70%'},
                       mce_attrs={
                           'storme_app_label':
                           CorpMembershipApp._meta.app_label,
                           'storme_model':
                           CorpMembershipApp._meta.module_name.lower()
                       }),
        help_text=_('Will show at the top of the application form.'))
    confirmation_text = forms.CharField(
        required=False,
        widget=TinyMCE(attrs={'style': 'width:70%'},
                       mce_attrs={
                           'storme_app_label':
                           CorpMembershipApp._meta.app_label,
                           'storme_model':
                           CorpMembershipApp._meta.module_name.lower()
                       }),
        help_text=_('Will show on the confirmation page.'))
    notes = forms.CharField(
        label=_('Notes'),
        required=False,
        widget=forms.Textarea(attrs={'rows': '3'}),
        help_text=_(
            'Notes for editor. Will not display on the application form.'))
    status_detail = forms.ChoiceField(choices=(
        ('active', _('Active')),
        ('inactive', _('Inactive')),
        ('admin hold', _('Admin Hold')),
    ))

    class Meta:
        model = CorpMembershipApp
        fields = (
            'name',
            'slug',
            'corp_memb_type',
            'authentication_method',
            'memb_app',
            'payment_methods',
            'include_tax',
            'tax_rate',
            'description',
            'confirmation_text',
            'notes',
            'allow_anonymous_view',
            'user_perms',
            'member_perms',
            'group_perms',
            'status_detail',
        )

    def __init__(self, *args, **kwargs):
        super(CorpMembershipAppForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['description'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
            self.fields['confirmation_text'].widget.mce_attrs[
                'app_instance_id'] = self.instance.pk
        else:
            self.fields['description'].widget.mce_attrs['app_instance_id'] = 0
            self.fields['confirmation_text'].widget.mce_attrs[
                'app_instance_id'] = 0

    def clean(self):
        cleaned_data = super(CorpMembershipAppForm, self).clean()
        is_public = cleaned_data.get('allow_anonymous_view')
        corp_memb_types = cleaned_data.get('corp_memb_type')

        if is_public and corp_memb_types:
            public_types = [
                not cm_type.admin_only for cm_type in corp_memb_types
            ]
            if not any(public_types):
                raise forms.ValidationError(
                    _('Please select a public corporate membership type. \
                    All types currently selected are admin only.'))

        return cleaned_data
コード例 #10
0
ファイル: forms.py プロジェクト: denyszamiatin/ma_book
class PostForm(forms.Form):
    title = forms.CharField(max_length=150, required=True, widget=forms.TextInput())
    text = forms.CharField(widget=forms.Textarea())
    image = forms.FileField(required=False, widget=forms.FileInput(attrs={'class': 'custom-file-input',
                                                             'id': 'post_image_input'
                                                             }))
コード例 #11
0
ファイル: forms.py プロジェクト: fireblackman/learnning
 class Meta:
     model = Entry
     fields = ['text']
     labels = {'text': ''}
     widgets = {'text': forms.Textarea(attrs={'cols': 80})}
コード例 #12
0
ファイル: forms.py プロジェクト: FixedOctocat/Vote_app
	class Meta:
		model = Poll
		fields = ['text', 'choice1', 'choice2']
		widgets = {
			'text': forms.Textarea(attrs={'class':"form-control", 'rows':5, 'cols':15})
		}
コード例 #13
0
ファイル: forms.py プロジェクト: smswarnambigai1/pyprodash
class EditorForm(forms.Form):

    form2edit = forms.CharField(label='', help_text='',
                                widget=forms.Textarea())
コード例 #14
0
ファイル: forms.py プロジェクト: guoyu07/sentry-jira
class JIRAOptionsForm(forms.Form):
    instance_url = forms.CharField(
        label=_("JIRA Instance URL"),
        widget=forms.TextInput(
            attrs={
                'class': 'span6',
                'placeholder': 'e.g. "https://jira.atlassian.com"'
            }),
        help_text=_("It must be visible to the Sentry server"),
        required=True)
    username = forms.CharField(
        label=_("Username"),
        widget=forms.TextInput(attrs={'class': 'span6'}),
        help_text=_("Ensure the JIRA user has admin perm. on the project"),
        required=True)
    password = forms.CharField(
        label=_("Password"),
        widget=forms.PasswordInput(attrs={'class': 'span6'}),
        help_text=_("Only enter a value if you wish to change it"),
        required=False)
    default_project = forms.ChoiceField(label=_("Linked Project"), )
    ignored_fields = forms.CharField(
        label=_("Ignored Fields"),
        widget=forms.Textarea(
            attrs={
                'class': 'span11',
                'placeholder': 'e.g. "components, security, customfield_10006"'
            }),
        help_text=
        _("Comma-separated list of properties that you don't want to show in the form"
          ),
        required=False)

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

        initial = kwargs.get("initial")
        project_safe = False
        if initial and initial.get("instance_url"):
            # make a connection to JIRA to fetch a default project.
            jira = JIRAClient(initial["instance_url"], initial.get("username"),
                              initial.get("password"))
            projects_response = jira.get_projects_list()
            if projects_response.status_code == 200:
                projects = projects_response.json
                if projects:
                    project_choices = [
                        (p.get('key'),
                         "%s (%s)" % (p.get('name'), p.get('key')))
                        for p in projects
                    ]
                    project_safe = True
                    self.fields["default_project"].choices = project_choices

        if not project_safe:
            del self.fields["default_project"]
            del self.fields["ignored_fields"]

    def clean_password(self):
        """
        Don't complain if the field is empty and a password is already stored,
        no one wants to type a pw in each time they want to change it.
        """
        pw = self.cleaned_data.get("password")
        if pw:
            return pw
        else:
            old_pw = self.initial.get("password")
            if not old_pw:
                raise ValidationError("A Password is Required")
            return old_pw

    def clean_instance_url(self):
        """
        Strip forward slashes off any url passed through the form.
        """
        url = self.cleaned_data.get("instance_url")
        if url and url[-1:] == "/":
            return url[:-1]
        else:
            return url

    def clean(self):
        """
        try and build a JIRAClient and make a random call to make sure the
        configuration is right.
        """
        cd = self.cleaned_data

        missing_fields = False
        if not cd.get("instance_url"):
            self.errors["instance_url"] = ["Instance URL is required"]
            missing_fields = True
        if not cd.get("username"):
            self.errors["username"] = ["Username is required"]
            missing_fields = True
        if missing_fields:
            raise ValidationError("Missing Fields")

        jira = JIRAClient(cd["instance_url"], cd["username"], cd["password"])
        sut_response = jira.get_priorities()
        if sut_response.status_code == 403 or sut_response.status_code == 401:
            self.errors["username"] = ["Username might be incorrect"]
            self.errors["password"] = ["Password might be incorrect"]
            raise ValidationError(
                "Unable to connect to JIRA: %s, if you have "
                "tried and failed multiple times you may have"
                " to enter a CAPTCHA in JIRA to re-enable API"
                " logins." % sut_response.status_code)
        elif sut_response.status_code == 500 or sut_response.json is None:
            raise ValidationError("Unable to connect to JIRA: Bad Response")
        elif sut_response.status_code > 200:
            raise ValidationError("Unable to connect to JIRA: %s" %
                                  sut_response.status_code)

        return cd
コード例 #15
0
ファイル: forms.py プロジェクト: lposada/TradeIt
class ContactForm(forms.Form):
    name = forms.CharField(label="Nombre", required=True, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Escribe tu Nombre.'}))
    email = forms.EmailField(label="Email", required=True, widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Escribe tu Correo.'}))
    content = forms.CharField(label="Contenido", required=True, widget=forms.Textarea(attrs={'class':'form-control', 'rows':3, 'placeholder':'Escribe tu mensaje.'}))
コード例 #16
0
class GroupForm(forms.ModelForm):
    description = forms.CharField(required=True, widget=forms.Textarea(attrs={'rows': 4, 'cols': 40}))

    class Meta:
        model = Group
        fields = ['name', 'description', 'photo']
コード例 #17
0
    class Meta:
        model = QuotationPrice
        fields = ('quotation_number', 'quotation_provider', 'date_create',
                  'date_validate', 'quotation_value', 'delivery_time',
                  'form_payment', 'comments', 'cancel_quotation',
                  'cancel_comments')

        labels = {
            'quotation_number': 'Cliente',
            'quotation_provider': 'Marcenaria',
            'date_create': 'Data do Orçamento',
            'date_validate': 'Validade do Orçamento',
            'quotation_value': 'Valor do Orçamento',
            'delivery_time': 'Prazo de Entrega',
            'form_payment': 'Forma de Pagamento.',
            'comments': 'Comentário da Marcenaria'
        }

        widgets = {
            'date_create':
            forms.DateInput(
                attrs={
                    'type': 'text',
                    'class': 'date_format',
                    'data-language': 'pt-BR',
                    'autocomplete': 'off',
                    'readonly': 'true',
                    'data-toggle': 'tooltip',
                    'data-placement': 'top',
                    'title': 'Data de lançamento da cotação.'
                }),
            'date_validate':
            forms.DateInput(
                attrs={
                    'type': 'text',
                    'class': 'datepicker-here date_format',
                    'data-language': 'pt-BR',
                    'data-position': 'bottom right',
                    'data-auto-close': 'true',
                    'autocomplete': 'off',
                    'data-toggle': 'tooltip',
                    'data-placement': 'top',
                    'title':
                    'Data de validade do valor orçado por sua empresa.'
                }),
            'quotation_value':
            forms.TextInput(
                attrs={
                    'class': 'dinheiro',
                    'autocomplete': 'off',
                    'data-toggle': 'tooltip',
                    'data-placement': 'top',
                    'title': 'Informe seu valor para esta cotação.'
                }),
            'delivery_time':
            forms.TextInput(
                attrs={
                    'autocomplete':
                    'on',
                    'data-toggle':
                    'tooltip',
                    'data-placement':
                    'top',
                    'title':
                    'Indique o total em dias para entrega do produto. Ex: "60 dias úteis".'
                }),
            'form_payment':
            forms.TextInput(
                attrs={
                    'autocomplete':
                    'on',
                    'data-toggle':
                    'tooltip',
                    'data-placement':
                    'top',
                    'title':
                    'Especifique aqui, a forma de pagamento usada por sua empresa.'
                }),
            'quotation_number':
            forms.TextInput(
                attrs={
                    'placeholder': 'Cliente desta cotação.',
                    'style': 'display: none;',
                    'title': ''
                }),
            'quotation_provider':
            forms.TextInput(
                attrs={
                    'placeholder': 'Fornecedor desta cotação',
                    'style': 'display: none;',
                    'title': ''
                }),
            'comments':
            forms.Textarea(
                attrs={
                    'cols':
                    40,
                    'style':
                    'width: 100%; height: 100%; resize: none; !important;',
                    'title':
                    '',
                    'placeholder':
                    'Obs: Se possuir ainda dúvidas sobre a cotação deste cliente, utilize o botão "Perguntar"'
                })
        }
コード例 #18
0
ファイル: forms.py プロジェクト: nchen/django-oscar
def _attr_textarea_field(attribute):
    return forms.CharField(label=attribute.name,
               widget=forms.Textarea(),
                           required=attribute.required)
コード例 #19
0
ファイル: forms.py プロジェクト: wjl626nice/1902
 class Meta:
     model = Followup_state
     fields = ['f_info']
     widgets = {
         'f_info': forms.Textarea(attrs={'class':'textarea','onkeyup':'$(this).Huitextarealength(this,200)','id':'info'}),
     }
コード例 #20
0
 class Meta:
     model = UserRank
     widgets = {
         'username_modifier': forms.Textarea(attrs={'class': 'post-editor'}),
     }
     fields = ('__all__')
コード例 #21
0
ファイル: forms.py プロジェクト: Ryanden/Django-Instagram
class SignupForm(forms.Form):

    username = forms.CharField(
        label='아이디',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control'
            }
        )
    )
    email = forms.EmailField(
        required=False,
        label='이메일',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control'
            }
        )
    )
    password = forms.CharField(
        label='비밀번호',
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control'
            }
        )
    )
    password2 = forms.CharField(
        label='비밀번호확인',
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control'
            }
        )
    )

    image_profile = forms.ImageField(
        required=False,
    )

    introduction = forms.CharField(
        required=False,
        label='자기소개',
        widget=forms.Textarea(
            attrs={
                'class': 'form-control'
            }
        )
    )

    gender = forms.ChoiceField(
        choices=(
            ('m', '남성'),
            ('f', '여성'),
            ('x', '선택안함'),
        )
    )

    site = forms.CharField(
        required=False,
        label='사이트',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control'
            }
        )
    )

    def clean_username(self):

        username = self.cleaned_data['username']
        reputation = User.objects.filter(username=username).exists()

        if reputation:
            raise ValidationError('이미 사용중인 아이디입니다.')

        return username

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

        if password != password2:
            self.add_error('password2', '비밀번호와 비밀번호 확인의 값이 일치하지 않습니다.')

        return self.cleaned_data

    def signup(self):
        fields = [
            'username',
            'email',
            'password',
            'img-profile',
            'introduction',
            'site',
        ]

        # create_user_dict = {key: value for key, value in self.cleaned_data.items() if key in fields}

        # def check(item):
        #     return item[0] in fields

        # create_user_dict = {}

        # create_user_dict = dict(filter(check, self.cleaned_data.items()))

        create_user_dict = dict(filter(lambda item: item[0] in fields, self.cleaned_data.items()))

        print(create_user_dict)

        user = User.objects.create_user(**create_user_dict)

        return user
コード例 #22
0
 class Meta:
     model = Subcategory
     widgets = {
         'description': forms.Textarea(attrs={'class': 'post-editor'})
     }
     fields = ('__all__')
コード例 #23
0
ファイル: forms.py プロジェクト: SanomaCZ/django-yummy
 def __init__(self, *args, **kwargs):
     super(CookBookEditForm, self).__init__(*args, **kwargs)
     self.fields['note'].widget = forms.Textarea()
コード例 #24
0
 class Meta:
     model = Message
     widgets = {
         'content': forms.Textarea(attrs={'class': 'post-editor'})
     }
     fields = ('__all__')
コード例 #25
0
ファイル: forms.py プロジェクト: katherinsb/test
class CheckForm(forms.Form):
	text = forms.CharField( widget=forms.Textarea())
コード例 #26
0
	class Meta:
		model = ProductionBlurb
		exclude = ['production']
		widgets = {
			'body': forms.Textarea(attrs={'class': 'short_notes'}),
		}
コード例 #27
0
class CommentModelForm(forms.ModelForm):
	comment = forms.CharField(label="", widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Comment here!', 'rows': '3', 'cols': '50'}))
	class Meta:
		model = Comment
		fields = ['comment']
コード例 #28
0
class ChapterForm(forms.Form):
    name = forms.CharField(max_length=30)
    description = forms.CharField(required=False, widget=forms.Textarea())
    document = forms.FileField(required=False)
コード例 #29
0
class MessageForm(forms.Form):
    text_input = forms.CharField()
    text_input_a = forms.CharField()
    text_input_b = forms.CharField()
    text_input_c = forms.CharField()

    textarea = forms.CharField(widget=forms.Textarea(), )

    radio_buttons = forms.ChoiceField(
        choices=
        (('option_one',
          "Option one is this and that be sure to include why it's great"),
         ('option_two',
          "Option two can is something else and selecting it will deselect option one"
          )),
        widget=forms.RadioSelect,
        initial='option_two',
    )

    checkboxes = forms.MultipleChoiceField(
        choices=
        (('option_one',
          "Option one is this and that be sure to include why it's great"),
         ('option_two',
          'Option two can also be checked and included in form results'),
         ('option_three',
          'Option three can yes, you guessed it also be checked and included in form results'
          )),
        initial='option_one',
        widget=forms.CheckboxSelectMultiple,
        help_text=
        "<strong>Note:</strong> Labels surround all the options for much larger click areas and a more usable form.",
    )

    grouped_checkboxes = forms.MultipleChoiceField(
        choices=(
            ('Group 1', ((1, "Option one"), (2, "Option two"),
                         (3, "Option three"))),
            ('Group 2', ((4, "Option four"), (5, "Option five"),
                         (6, "Option six"))),
        ),
        initial=(1, ),
        widget=forms.CheckboxSelectMultiple,
    )

    multicolon_select = forms.MultipleChoiceField(
        choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')), )

    # Bootstrap4
    helper = FormHelper()
    helper.layout = Layout(
        Field('text_input'), Field('textarea'), 'radio_buttons',
        Field('checkboxes', style="background: #FAFAFA"),
        Row(
            Column('text_input_a', 'text_input_b'),
            Column('text_input_c'),
        ),
        FormActions(
            Submit('save_changes', 'Save changes', css_class="btn-primary"),
            Submit('cancel', 'Cancel'),
        ))
コード例 #30
0
ファイル: forms.py プロジェクト: enier290188/hpc.v2
            'aria-describedby': 'password_confirmation_icon',
            'icon': 'fa fa-lock',
        },
        render_value=False,
    ),
)
FIELD_LOGIN_REQUEST_DETAIL = forms.CharField(
    label=_('SECURITY_LOGIN_REQUEST_DETAIL'),
    required=True,
    min_length=1,
    max_length=1024,
    widget=forms.Textarea(
        attrs={
            'id': 'detail',
            'class': 'form-control',
            'aria-describedby': 'detail_icon',
            'icon': 'fa fa-globe',
            'rows': 5,
        },
    ),
)
FIELD_PROFILE_AVATAR = forms.ImageField(
    label=_('SECURITY_PROFILE_AVATAR'),
    required=False,
    widget=forms.FileInput(
        attrs={
            'id': 'avatar',
            'icon': 'fa fa-picture-o',
            'id_button_upload': 'avatar-button-upload',
            'id_image_upload': 'avatar-image-upload',
            'style': 'display: none;',