Beispiel #1
0
 class Meta:
     model = Post
     is_multipart = True
     fields = ('name', 'photo', 'user_score', 'info', 'rubric',
               'show_authorship')
     widgets = {
         'name':
         Input(attrs={
             'class': 'sections',
             'id': 'name',
             'spellcheck': 'false'
         }),
         'rubric':
         Select(attrs={
             'class': 'sections',
             'id': 'rubrics'
         }),
         'photo':
         FileInput(
             attrs={
                 'class': 'sections',
                 'id': 'photo',
                 'type': 'file',
                 'name': 'photo'
             }),
         'user_score':
         NumberInput(
             attrs={
                 'class': 'sections',
                 'id': 'din',
                 'type': 'number',
                 'name': 'assesiment',
                 'min': '1',
                 'max': '10',
                 'step': '0.1'
             }),
         'info':
         Textarea(attrs={
             'name': 'link',
             'id': 'info',
             'class': 'sections'
         }),
         'show_authorship':
         CheckboxInput()
     }
Beispiel #2
0
class CSVImportForm(CSVMixin, forms.Form):
    """Form to upload a csv file. """
    HEADERS = {
        'price': {
            'field': 'price',
            'required': True
        },
        'brand': {
            'field': 'brand',
            'required': True
        },
        'title': {
            'field': 'title',
            'required': True
        },
        'category': {
            'field': 'category',
            'required': True
        },
    }

    CHOICES = (('csv', 'csv file'), )

    input_type = forms.ChoiceField(
        label='Select available type',
        choices=CHOICES,
        required=True,
        widget=forms.RadioSelect(attrs={'required': 'true'}))
    uploaded_file = forms.FileField(label='Find the list')
    kiosk = forms.ModelChoiceField(
        queryset=None,
        label='Select your Kiosk',
        required=True,
        widget=Select(attrs={'class': 'form-control'}))

    def __init__(self, *args, **kwargs):
        """Uses keyword ``managerid`` to ensure that displayed
        department choices will be only related to requested
        manager.
        """
        kiosk = kwargs.pop('kiosk', None)
        super(CSVImportForm, self).__init__(*args, **kwargs)
        if not kiosk:
            raise Exception('No kiosk was related')
        self.fields['kiosk'].queryset = kiosk.all()
Beispiel #3
0
    def add_fields(self, form, index):
        """ Ensure translation form has a language_code field """
        super(BaseTranslationFormSet, self).add_fields(form, index)
        # Add the language code automagically
        if not 'language_code' in form.fields:
            form.fields['language_code'] = CharField(
                required=True, initial=form.instance.language_code,
                widget=Select(choices=(('', '--'),)+hvad_settings.LANGUAGES)
            )
            # Add language_code to self._meta.fields so it is included in validation stage
            try:
                form._meta.fields.append('language_code')
            except AttributeError: #pragma: no cover
                form._meta.fields += ('language_code',)

        # Remove the master foreignkey, we have this from self.instance already
        if 'master' in form.fields:
            del form.fields['master']
Beispiel #4
0
    def get_form_field_instances(self,
                                 request=None,
                                 form_entry=None,
                                 form_element_entries=None,
                                 **kwargs):
        """Get form field instances."""
        choices = self.get_choices()

        field_kwargs = {
            'label': self.data.label,
            'help_text': self.data.help_text,
            'initial': self.data.initial,
            'required': self.data.required,
            'choices': choices,
            'widget': Select(attrs={'class': theme.form_element_html_class}),
        }

        return [(self.data.name, ChoiceField, field_kwargs)]
Beispiel #5
0
    def get_form_field_instances(self, request=None):
        """
        Get form field instances.
        """
        app_label, model_name = get_app_label_and_model_name(self.data.model)
        model = get_model(app_label, model_name)
        queryset = model._default_manager.all()

        kwargs = {
            'label': self.data.label,
            'help_text': self.data.help_text,
            'initial': self.data.initial,
            'required': self.data.required,
            'queryset': queryset,
            'widget': Select(attrs={'class': theme.form_element_html_class}),
        }

        return [(self.data.name, TreeNodeChoiceField, kwargs)]
Beispiel #6
0
    def __init__(self, choices=None, attrs=None, widgets=None,
                 widget_css_class='choice-and-char-widget', **kwargs):

        if not attrs:
            attrs = {}

        if not widgets:
            widgets = (
                Select(choices=choices),
                TextInput()
            )

        super(ChoiceAndCharInputWidget, self).__init__(
            widgets=widgets,
            attrs=attrs,
            widget_css_class=widget_css_class,
            **kwargs
        )
Beispiel #7
0
 def __init__(self, *args, **kwargs):
     super(ProcessingConfigurationForm, self).__init__(*args, **kwargs)
     for choice_uuid, field in self.processing_fields.items():
         ftype = field['type']
         opts = self.DEFAULT_FIELD_OPTS.copy()
         if 'label' in field:
             opts['label'] = field['label']
         if ftype == 'days':
             if 'min_value' in field:
                 opts['min_value'] = field['min_value']
             self.fields[choice_uuid] = forms.IntegerField(**opts)
             if 'placeholder' in field:
                 self.fields[choice_uuid].widget.attrs[
                     'placeholder'] = field['placeholder']
             self.fields[choice_uuid].widget.attrs['class'] = 'form-control'
         else:
             choices = opts['choices'] = list(self.EMPTY_CHOICES)
             if ftype == 'boolean':
                 if 'yes_option' in field:
                     choices.append((field['yes_option'], 'Yes'))
                 if 'no_option' in field:
                     choices.append((field['no_option'], 'No'))
             elif ftype == 'chain_choice':
                 chain_choices = models.MicroServiceChainChoice.objects.filter(
                     choiceavailableatlink_id=choice_uuid)
                 ignored_choices = field.get('ignored_choices', [])
                 for item in chain_choices:
                     chain = item.chainavailable
                     if chain.description in ignored_choices:
                         continue
                     choices.append((chain.pk, chain.description))
             elif ftype == 'replace_dict':
                 link = models.MicroServiceChainLink.objects.get(
                     pk=choice_uuid)
                 replace_dicts = models.MicroServiceChoiceReplacementDic.objects.filter(
                     choiceavailableatlink_id=link.pk)
                 for item in replace_dicts:
                     choices.append((item.pk, item.description))
             elif ftype == 'storage_service':
                 for loc in get_storage_locations(purpose=field['purpose']):
                     choices.append(
                         (loc['resource_uri'], loc['description']))
             self.fields[choice_uuid] = forms.ChoiceField(
                 widget=Select(attrs={'class': 'form-control'}), **opts)
Beispiel #8
0
class PerplexityForm(forms.Form):
    param = forms.CharField(required=False,
                            label='parameter',
                            widget=Select(choices=(('ntopics',
                                                    'Number of Topics'),
                                                   ('someother', ''))))
    folds = forms.IntegerField(
        required=True,
        label='number of folds',
        initial='1',
        min_value=1,
        max_value=10,
        widget=forms.TextInput(attrs={"class": "small_int"}),
        help_text="k-fold perplexity calculation")
    pertest = forms.IntegerField(
        required=False,
        label='percent test',
        initial='20',
        min_value=1,
        max_value=99,
        widget=forms.TextInput(attrs={"class": "small_int"}),
        help_text="% of hold-out data if number of folds=1")
    start = forms.IntegerField(
        required=True,
        label='parameter range',
        initial='5',
        min_value=1,
        widget=forms.TextInput(attrs={"class": "small_int"}),
        help_text="start : increment: end")
    stop = forms.IntegerField(
        required=True,
        label='stop',
        initial='15',
        widget=forms.TextInput(attrs={"class": "small_int"}))
    step = forms.IntegerField(
        required=True,
        label='step',
        initial='10',
        min_value=1,
        widget=forms.TextInput(attrs={"class": "small_int"}))
    current_step = forms.IntegerField(required=False,
                                      label="current iteration (ajax helper)")
    current_fold = forms.IntegerField(required=False,
                                      label="current fold (ajax helper)")
Beispiel #9
0
    def render(self, context):
        if context.has_key(self.choice_list):
            choice_list = context[self.choice_list]
        else:
            raise ValueError, "Can't find key %s in the context" % (
                self.choice_list)

        print "self.selected_item = %s" % (self.selected_item)

        if self.selected_item != None:
            if context.has_key(self.selected_item):
                selected_item = context[self.selected_item]
            else:
                raise ValueError, "Can't find key %s in the context" % (
                    self.selected_item)
        else:
            selected_item = None

        return Select().render_options(choice_list, [selected_item])
Beispiel #10
0
    def __init__(self, *args, **kwargs):
        super(modificarusuarioForm, self).__init__(*args, **kwargs)

        self.fields['username'].error_messages = {
            'required': 'El nombre de Usuario no es valido!'
        }
        self.fields['password'].error_messages = {
            'required': 'El password ingresado no es valido!'
        }
        self.fields['email'].error_messages = {
            'required': 'La direccion de E-mail ingresada no es correcta!'
        }

        self.fields['password'].widget = PasswordInput()
        ACTIVO = ((True, 'Activo'), (False, 'Inactivo'))
        self.fields['is_active'].widget = Select(choices=ACTIVO)
        self.fields['numeroDoc'].widget.attrs['maxlength'] = 8
        self.fields['permisos'].widget.attrs[
            'class'] = 'permisosSelect centrar'
Beispiel #11
0
class FilterMediation(Form):

    searchtext = CharField(
        label=_("SEARCH_TEXT"),
        required=False,
        widget=TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('SEARCH_TITLE_AND_TAGS')
        }))

    ordering = ChoiceField(choices=[
        ('REWARD_HIGHEST', _('REWARD_HIGHEST')),
        ('REWARD_LOWEST', _('REWARD_LOWEST')),
        ('DEADLINE_NEAREST', _('DEADLINE_NEAREST')),
        ('DEADLINE_FARTHEST', _('DEADLINE_FARTHEST')),
    ],
                           label=_("ORDERING"),
                           initial="REWARD_HIGHEST",
                           widget=Select(attrs={'class': 'form-control'}))
Beispiel #12
0
    def render(self, name, value, attrs=None, renderer=None):
        try:
            year_val, month_val, day_val = value.year, value.month, value.day
        except AttributeError:
            year_val = month_val = day_val = None
            if isinstance(value, (str, bytes)):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val = [
                        int(v) for v in match.groups()
                    ]

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        # Day input
        local_attrs = self.build_attrs({'id': self.day_field % id_})
        s = NumberInput(attrs={'class': 'form-control', 'placeholder': 'Day'})
        select_html = s.render(self.day_field % name, day_val, local_attrs)
        output.append(self.sqeeze_form_group(select_html))

        # Month input
        if hasattr(self, 'month_choices'):
            local_attrs = self.build_attrs({'id': self.month_field % id_})
            s = Select(choices=self.month_choices,
                       attrs={'class': 'form-control'})
            select_html = s.render(self.month_field % name, month_val,
                                   local_attrs)
            output.append(self.sqeeze_form_group(select_html))

        # Year input
        local_attrs = self.build_attrs({'id': self.year_field % id_})
        s = NumberInput(attrs={'class': 'form-control', 'placeholder': 'Year'})
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        output.append(self.sqeeze_form_group(select_html))

        output = '<div class="row mb-0">{0}</div>'.format(u'\n'.join(output))

        return mark_safe(output)
Beispiel #13
0
    def __init__(self, attrs=None, date_format=None, time_format=None):
        date_class = attrs["date_class"]
        time_class = attrs["time_class"]
        del attrs["date_class"]
        del attrs["time_class"]

        time_attrs = attrs.copy()
        time_attrs["class"] = time_class
        date_attrs = attrs.copy()
        date_attrs["class"] = date_class

        widgets = (
            DateInput(attrs=date_attrs, format=date_format),
            TextInput(attrs=time_attrs),
            TextInput(attrs=time_attrs),
            Select(attrs=attrs, choices=[("AM", "AM"), ("PM", "PM")]),
        )

        super(JqSplitDateTimeWidget, self).__init__(widgets, attrs)
Beispiel #14
0
 class Meta:
     model = ementas
     fields = [
         'menu',
         'sopa',
         'pratoCarne',
         'pratoPeixe',
         'pratoVegetariano',
         'sobremesa',
     ]
     widgets = {
         'menu': Select(attrs={'class': 'form-control'}),
         'sopa': forms.TextInput(attrs={'class': 'form-control'}),
         'pratoCarne': forms.TextInput(attrs={'class': 'form-control'}),
         'pratoPeixe': forms.TextInput(attrs={'class': 'form-control'}),
         'pratoVegetariano':
         forms.TextInput(attrs={'class': 'form-control'}),
         'sobremesa': forms.TextInput(attrs={'class': 'form-control'}),
     }
Beispiel #15
0
def field_changed(request):
    """
    Ajax callback called when a trigger field or base field has changed.
    Returns html for new options and details for the dependent field as json.
    """
    hashed_name = request.POST.get('hashed_name')
    app_label, model_name, base_field_name = hashed_name.split('__')
    model = apps.get_model(app_label, model_name)
    obj = FlexSelectWidget.object_from_post(model, request.POST)
    value_fk = getattr(obj, base_field_name)
    admin_instance = admin.site._registry[obj.__class__]
    base_field = next(f for f in obj._meta.fields if f.name == base_field_name)
    widget = admin_instance.formfield_for_dbfield(
        base_field,
        request=request,
    ).widget.widget

    if bool(int(request.POST['include_options'])):
        if widget.choice_function:
            choices = widget.choice_function(obj)
        else:
            choices = choices_from_instance(obj, widget)

        args = [[value_fk.pk if value_fk else None]]
        if DJANGO_VERSION < (1, 10, 0):
            args.insert(0, [])
        if DJANGO_VERSION < (1, 11, 0):
            options = Select(choices=choices).render_options(*args)
        else:
            # django 1.11 has introduced template rednering for widgets
            widget.choices = choices
            val = value_fk.pk if value_fk else None
            options = widget.render_options_template(val, widget.attrs)
    else:
        options = None

    return HttpResponse(json.dumps({
        'options':
        options,
        'details':
        details_from_instance(obj, widget),
    }),
                        content_type='application/json')
Beispiel #16
0
 class Meta:
     model = Passport
     fields = [
         'serial',
         'number',
         'v_from',
         'date_of',
         'gender',
         'birthday',
         'code_of',
     ]
     labels = {
         'serial': 'Серия',
         'number': 'Номер',
         'v_from': 'Кем выдан',
         'gender': 'пол',
         'birthday': 'Дата рождения',
         'date_of': 'Дата выдачи',
         'code_of': 'Код подразделения',
     }
     widgets = {
         'serial':
         simpleInput,
         'number':
         simpleInput,
         'v_from':
         Textarea(attrs={
             'class': 'form-control',
             'style': 'height: 95px;'
         }),
         'gender':
         Select(attrs={
             'class': 'form-control',
             'choices': 'small2'
         },
                choices=GENDER_CHOISES),
         'birthday':
         simpleDate,
         'date_of':
         simpleDate,
         'code_of':
         simpleInput,
     }
Beispiel #17
0
class BbForm_Full(ModelForm):
    """
    Форма для ввода новых объявлений.
    Создание формы путём полного объявления.
    """
    title = forms.CharField(
        label='Название товара',
        # Содержит ли название более 4-х символов
        validators=[RegexValidator(regex='^.{4,}$')],
        error_messages={'invalid': 'Слишком короткое название товара!'})
    content = forms.CharField(label='Описание', widget=Textarea())
    price = forms.DecimalField(label='Цена', decimal_places=2)
    rubric = forms.ModelChoiceField(queryset=Rubric.objects.all(),
                                    label='Рубрика',
                                    help_text='Не забудьте задать рубрику!',
                                    widget=Select(attrs={'size': 6}))

    def clean_title(self):
        """Валидация ПОЛЯ (title), путём переопределения методов формы"""
        # Получаем значение интересующего поля из словаря
        val = self.cleaned_data['title']
        # Проверяем значение на заданный паттерн
        if val == 'Прошлогодний снег':
            # Если совподает - вызываем ошибку
            raise ValidationError('К продаже не допускается!')
        return val  # возврат значения проверяемого поля!

    def clean(self):
        """Валидация ВСЕЙ формы (выбранных ниже полей)"""
        super().clean()
        errors = {}
        if not self.cleaned_data['content']:
            errors['content'] = ValidationError('Укажите описание товара!')
        if self.cleaned_data['price'] < 0:
            errors['price'] = ValidationError(
                'Укажите неотрицательное значение цены!')

        if errors:
            raise ValidationError(errors)

    class Meta:
        model = Bb
        fields = ('title', 'content', 'price', 'rubric')
Beispiel #18
0
 def __init__(self, attrs, *args, **kwargs):
     imagelist = []
     a = historical_team.objects.all().filter(coach1=attrs['user']).exclude(
         logo__contains="defaultleaguelogo").exclude(
             logo__contains="defaultteamlogo").order_by('logo').distinct(
                 'logo')
     for item in a:
         imagelist.append((f'h_{item.id}', item.logourl))
     a = coachdata.objects.all().filter(coach=attrs['user']).exclude(
         logo__contains="defaultleaguelogo").exclude(
             logo__contains="defaultteamlogo").order_by('logo').distinct(
                 'logo')
     for item in a:
         imagelist.append((f'c_{item.id}', item.logourl))
     widgets = [
         Select(choices=imagelist),
         FileInput(),
     ]
     super().__init__(widgets, attrs, *args, **kwargs)
Beispiel #19
0
class ssh_resource_Form(forms.Form):

    #Mandatory form fields

    inftype = forms.CharField(widget=forms.HiddenInput, initial='ssh_resource')
    infid = forms.CharField(widget=forms.HiddenInput, initial='0')
    jobid = forms.CharField(widget=forms.HiddenInput, initial='0')

    machine = forms.CharField(initial='Hostname')

    sshpubkey = forms.CharField(label="SSH pub key",
                                widget=forms.Textarea,
                                initial='paste your id_rsa.key')
    username = forms.CharField(initial='')

    #optional form fields if globus get file field  for proxy
    add_another        = forms.ChoiceField(widget=Select(), \
                         label = "Add another Resource",choices=[['false','False'], \
                         ['true','True']] )
Beispiel #20
0
    def __init__(self, attrs=None):
        freqOptions = [(DAILY,   _("Daily")),
                       (WEEKLY,  _("Weekly")),
                       (MONTHLY, _("Monthly")),
                       (YEARLY,  _("Yearly"))]
        ordOptions1 = [(1,  toTheOrdinal(1)),
                       (2,  toTheOrdinal(2)),
                       (3,  toTheOrdinal(3)),
                       (4,  toTheOrdinal(4)),
                       (5,  toTheOrdinal(5)),
                       (-1, toTheOrdinal(-1)),
                       (EVERY_DAY, _("Every")),
                       (SAME_DAY, _("The Same"))]
        ordOptions2 = [(None, ""),
                       (1,    toTheOrdinal(1)),
                       (2,    toTheOrdinal(2)),
                       (3,    toTheOrdinal(3)),
                       (4,    toTheOrdinal(4)),
                       (5,    toTheOrdinal(5)),
                       (-1,   toTheOrdinal(-1))]
        dayOptions1  = enumerate(WEEKDAY_ABBRS)
        dayOptions2  = [(None, "")] + list(enumerate(WEEKDAY_NAMES))
        dayOptions3  = list(enumerate(WEEKDAY_NAMES)) +\
                       [(DAY_OF_MONTH, _("Day of the month"))]
        monthOptions = enumerate(MONTH_ABBRS[1:], 1)

        numAttrs = {'min': 1, 'max': 366}
        disableAttrs = {'disabled': True}
        if attrs:
            numAttrs.update(attrs)
            disableAttrs.update(attrs)
        widgets = [AdminDateInput(attrs=attrs),
                   Select(attrs=attrs, choices=freqOptions),         #1
                   NumberInput(attrs=numAttrs),
                   CheckboxSelectMultiple(attrs=attrs, choices=dayOptions1),
                   NumberInput(attrs=numAttrs),
                   AdminDateInput(attrs=attrs),                      #5
                   Select(attrs=attrs, choices=ordOptions1),
                   Select(attrs=attrs, choices=dayOptions3),
                   Select(attrs=disableAttrs, choices=ordOptions2),
                   Select(attrs=disableAttrs, choices=dayOptions2),
                   Select(attrs=disableAttrs, choices=ordOptions2),  #10
                   Select(attrs=disableAttrs, choices=dayOptions2),
                   CheckboxSelectMultiple(attrs=attrs, choices=monthOptions) ]
        super().__init__(widgets, attrs)
Beispiel #21
0
class AssignTicketForm(ModelForm):
    """Accept and Assign or re-assign a ticket and provide a
    comment."""

    comment = CharField(
        widget=Textarea(attrs={"class": "form-control"}),
        help_text=
        "Comment field accepts markdown that will be converted to html.",
    )

    assigned_to = UserModelChoiceField(
        # queryset=User.objects.filter(groups__name='admin'),
        queryset=User.objects.filter(is_staff=True),
        label="Assign To",
        required=True,
        widget=Select(attrs={"class": "form-select"}),
    )

    def __init__(self, *args, **kwargs):

        self.user = kwargs.pop("user")
        self.ticket = kwargs.pop("ticket")
        super(AssignTicketForm, self).__init__(*args, **kwargs)
        if self.ticket.assigned_to:
            self.initial["assigned_to"] = self.ticket.assigned_to

    def save(self, *args, **kwargs):
        followUp = FollowUp(
            ticket=self.ticket,
            submitted_by=self.user,
            comment=self.cleaned_data["comment"],
        )

        assigned_to = self.cleaned_data.get("assigned_to")
        self.ticket.assigned_to = assigned_to
        self.ticket.status = "assigned"
        self.ticket.save()
        followUp.save()

    class Meta:
        model = FollowUp
        fields = ["comment"]
Beispiel #22
0
class ImageAnnotationForm(forms.Form):
    status_list = Status.objects.filter(default=True)

    if status_list:
        default_status = status_list[0]

    #status = forms.ModelChoiceField(queryset=Status.objects.all(),
    #        initial=default_status)
    hand = forms.ModelChoiceField(required=False, queryset=Hand.objects.all(),
        widget = Select(attrs={'name': 'hand', 'class':'chzn-select hand_form', 'data-placeholder':"Hand"}),
        label = "",
        empty_label = '------',
        )
    #after = forms.ModelChoiceField(required=False,
    #        queryset=Allograph.objects.all())
    allograph = forms.ModelChoiceField(required=False, queryset=Allograph.objects.all(),
        widget = AllographSelect(attrs={'name': 'allograph', 'class':'chzn-select allograph_form', 'data-placeholder':"Allograph"}),
        label = "",
        empty_label = '------',
    )
    #before = forms.ModelChoiceField(required=False,
    #        queryset=Allograph.objects.all())
    #feature = forms.MultipleChoiceField(required=False,
    #        widget=forms.SelectMultiple(attrs={'size': 25}))
    display_note = forms.CharField(required=False,
                                   label = "",
            widget=Textarea(attrs={'cols': 25, 'rows': 5, 'class':'hidden'}))
    internal_note = forms.CharField(required=False,
                                    label = "",
            widget=Textarea(attrs={'cols': 25, 'rows': 5, 'class':'hidden'}))

    def clean(self):
        """The feature field is always marked as invalid because the choices
        are populated dinamically on the client side, therefore the clean
        method needs to be overriden to ignore errors related to the feature
        field."""
        super(ImageAnnotationForm, self).clean()

        if 'feature' in self._errors:
            del self._errors['feature']

        return self.cleaned_data
Beispiel #23
0
def dashboard(request):
  queryset = Exercise.objects.all().order_by('name')
  exercises = []

  for row in queryset:
    tmp_tpl = (row.id, row.name)
    exercises.append(tmp_tpl)

  select = Select(choices=exercises, attrs={'id':'exercise_id'})
  exercise_select = select.render('exercise', 1) # 1 = push ups

  rows = Set.objects.filter(user = request.user).order_by('ts')

  rep_counts = {}

  reps_remaining = 36525;

  for row in rows:
    pprint(row)
    pprint(row.reps)
    pprint(row.exercise.name)
    if not row.exercise.name in rep_counts:
      rep_counts[row.exercise.name] = row.reps
    else:
      rep_counts[row.exercise.name] += row.reps

    reps_remaining -= row.reps

  pprint(rep_counts)






  context = {
    'exercise_select' : exercise_select,
    'rep_counts': rep_counts,
    'reps_remaining': reps_remaining
  }

  return render(request, 'web/dashboard.html', context)
Beispiel #24
0
class chamado_hseForm(ModelForm):
    tipo_servico = forms.MultipleChoiceField(
        choices=TYPE_CHOICES,
        widget=forms.CheckboxSelectMultiple(attrs={
            'class': 'flat',
            'name': '',
            'type': 'checkbox'
        }))
    empresa = forms.ModelChoiceField(queryset=empresa_terc.objects.all(),
                                     widget=Select(
                                         attrs={
                                             'class': 'form-control',
                                             'data-show-subtext': 'true',
                                             'data-live-search': 'true'
                                         }))

    #resp_terc = forms.ModelChoiceField(queryset=cad_resp.objects.all(), widget=Select(attrs={'class':'form-control', 'data-show-subtext':'true', 'data-live-search':'true'}))

    nome_proj = forms.CharField(
        label="Nome Projeto / Serviço ",
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'name': 'vencimento',
            'type': ''
        }))

    descricao = forms.CharField(
        label="Descricao",
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'name': 'descricao',
            'type': 'textarea'
        }))

    class Meta:
        model = chamado_hse
        fields = [
            'empresa',
            'nome_proj',
            'tipo_servico',
            'descricao',
        ]
Beispiel #25
0
class TrainingSelectForm(forms.Form):
    captcha = NoReCaptchaField()
    training_first = ModelChoiceField(
        queryset=None,
        widget=Select(attrs={'id': 'country'})
    )
    #agreement = forms.BooleanField(widget=forms.CheckboxInput(attrs={'style':'width: 20px;'}))

    def __init__(self, *args, **kwargs):
        super(TrainingSelectForm, self).__init__(*args, **kwargs)
        date_setting = Setting.objects.only('training_finish_date').get()
        training_list = []
        for i in Training.objects.all():
            if i.limitless is True and date_setting.training_finish_date >= timezone.localtime(timezone.now()).date():
                training_list.append(i.id)
            elif i.limitless is False and UserTraining.objects.filter(first_selection=i).count() < (
                    i.capacity * 2) and date_setting.training_finish_date >= timezone.localtime(timezone.now()).date():
                training_list.append(i.id)
        self.fields['training_first'].queryset = Training.objects.filter(pk__in=training_list)
        self.fields['training_first'].empty_label = 'Almak istediğiniz eğitimi seçiniz.'
Beispiel #26
0
    class Meta:
        model = Persona
        fields = ('nombre', 'apellido', 'email', 'celular',
                  'region')
        widgets = {
            'nombre': Textarea(attrs={'rows': 1, 'cols': 30, 'style': 'resize:none;', 'id': 'nombre', 'class': 'form-control', 'required onfocus': "setVisibility('100','inline')", 'onBlur': "setVisibility('100','none')",  'onkeyup':"sync()"}),
            'apellido': Textarea(attrs={'rows': 1, 'cols': 30, 'style': 'resize:none;', 'id': 'apellido', 'class': "form-control", 'required onfocus': "setVisibility('101','inline')", 'onBlur': "setVisibility('101','none')",  'onkeyup':"sync()"}),
            'email': EmailInput(attrs={'rows': 1, 'cols': 30, 'style': 'resize:none;', 'id': 'email', 'class': "form-control", 'required onfocus': "setVisibility('102','inline')", 'onBlur': "setVisibility('102','none')", 'type': 'email',  'onkeyup':"sync()"}),
            'celular': Textarea(attrs={'rows': 1, 'cols': 30, 'style': 'resize:none;', 'id': 'celular', 'class': "form-control", 'required onfocus': "setVisibility('103','inline')", 'onBlur': "setVisibility('103','none')"}),
            'region': Select(attrs={'class': "form-control", 'onfocus': "setVisibility('105','inline')", 'onBlur': "setVisibility('105','none')", 'default': "rm"}),
          }

        labels = {
            'nombre': _('Nombre'),
            'apellido': _('Apellido'),
            'email': _('Correo Electronico'),
            'celular': _('Numero Telefonico'),
            'region': _('Region'),

        }
Beispiel #27
0
class ConditionForm(forms.Form):

    negative_widget = Select(choices=((False, 'Is'), (True, 'Is Not')))

    argument = forms.ChoiceField(choices=arguments.as_choices)
    negative = forms.BooleanField(widget=negative_widget, required=False)
    operator = forms.ChoiceField(choices=operators.as_choices,
                                 widget=OperatorSelectWidget(
                                     operators.arguments))

    @staticmethod
    def to_dict(condition):
        fields = dict(argument='.'.join(
            (condition.argument.__name__, condition.attribute)),
                      negative=condition.negative,
                      operator=condition.operator.name)

        fields.update(condition.operator.variables)

        return fields
Beispiel #28
0
 class Meta:
     model = Projects     
     fields = ('project_name', 'project_desc', 'detect_model', 'ibm_service_url', 'ibm_api_key', 'offline_model', 'image', 'public')
     labels = {
         'project_name': _('Project Name'),
         'project_desc': _('Description'),
         'image': _("Project Image"),
         'detect_model': _("Online Object Detect Model"),
         'offline_model': _("Offline Object Detect Model"),
         'ibm_api_key': _("IBM API KEY"),
         'ibm_service_url': _("IBM Service URL"),
         'public': _('Is Publicly Visible')
     }
     widgets = {
       'project_desc': Textarea(attrs={'rows':4, 'cols':20}),
       'detect_model': Textarea(attrs={'rows':1, 'cols':20, 'placeholder':'Default: '+detect_object_model_id}),
       'ibm_api_key': Input(attrs={'placeholder':'Enter your IBM Watson API Key'}),
       'ibm_service_url': Input(attrs={'placeholder':'Enter a valid IBM Service URL'}),
       'offline_model': Select(attrs={'placeholder':'Select Offline Model'}),
     }
Beispiel #29
0
    def get_form_field_instances(self,
                                 request=None,
                                 form_entry=None,
                                 form_element_entries=None,
                                 **kwargs):
        """Get form field instances."""
        app_label, model_name = self.data.model.split('.')
        model = models.get_model(app_label, model_name)
        queryset = model._default_manager.all()

        field_kwargs = {
            'label': self.data.label,
            'help_text': self.data.help_text,
            'initial': self.data.initial,
            'required': self.data.required,
            'queryset': queryset,
            'widget': Select(attrs={'class': theme.form_element_html_class}),
        }

        return [(self.data.name, ModelChoiceField, field_kwargs)]
class UserRegistrationForm(UserCreationForm):
    use_required_attribute = False

    organization_code = UserOrganizationField(
        queryset=Organization.objects.exclude_vendors().order_by(
            'organization_name'),
        widget=Select(attrs={'id': 'id_user_organization_code'}),
        to_field_name='organization_code',
        required=False,
        help_text=
        'Begin to enter the common name of your organization to choose from the list. '
        'If "No results found", then clear your entry, click on the drop-down-list to select '
        '"Add New Organization".')
    agreement = forms.BooleanField(required=True)

    class Meta:
        model = User
        fields = [
            'first_name', 'last_name', 'email', 'username', 'organization_code'
        ]