コード例 #1
0
class ContributionForm(forms.ModelForm):
    contributor = UserModelChoiceField(
        queryset=UserProfile.objects.exclude_inactive_users())
    responsibility = forms.ChoiceField(
        widget=forms.RadioSelect(),
        choices=Contribution.RESPONSIBILITY_CHOICES)
    evaluation = forms.ModelChoiceField(Evaluation.objects.all(),
                                        disabled=True,
                                        required=False,
                                        widget=forms.HiddenInput())
    questionnaires = forms.ModelMultipleChoiceField(
        Questionnaire.objects.contributor_questionnaires().filter(
            obsolete=False),
        required=False,
        widget=CheckboxSelectMultiple,
        label=_("Questionnaires"))
    does_not_contribute = forms.BooleanField(
        required=False, label=_("Does not contribute to evaluation"))

    class Meta:
        model = Contribution
        fields = ('evaluation', 'contributor', 'questionnaires', 'order',
                  'responsibility', 'textanswer_visibility', 'label')
        widgets = {
            'order':
            forms.HiddenInput(),
            'textanswer_visibility':
            forms.RadioSelect(
                choices=Contribution.TEXTANSWER_VISIBILITY_CHOICES)
        }

    def __init__(self, *args, evaluation=None, **kwargs):
        self.evaluation = evaluation
        # work around https://code.djangoproject.com/ticket/25880
        if self.evaluation is None:
            assert 'instance' in kwargs
            self.evaluation = kwargs['instance'].evaluation

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

        if self.instance.can_edit:
            self.fields['responsibility'].initial = Contribution.IS_EDITOR
        else:
            self.fields['responsibility'].initial = Contribution.IS_CONTRIBUTOR

        if self.instance.contributor:
            self.fields['contributor'].queryset |= UserProfile.objects.filter(
                pk=self.instance.contributor.pk)

        self.fields[
            'questionnaires'].queryset = Questionnaire.objects.contributor_questionnaires(
            ).filter(
                Q(obsolete=False)
                | Q(contributions__evaluation=self.evaluation)).distinct()

        if self.instance.pk:
            self.fields[
                'does_not_contribute'].initial = not self.instance.questionnaires.exists(
                )

        if self.evaluation.pk and not self.evaluation.can_be_edited_by_manager:
            # form is used as read-only evaluation view
            disable_all_fields(self)

    def clean(self):
        if not self.cleaned_data.get(
                'does_not_contribute') and not self.cleaned_data.get(
                    'questionnaires'):
            self.add_error(
                'does_not_contribute',
                _("Select either this option or at least one questionnaire!"))

    def save(self, *args, **kwargs):
        responsibility = self.cleaned_data['responsibility']
        is_editor = responsibility == Contribution.IS_EDITOR
        self.instance.can_edit = is_editor
        return super().save(*args, **kwargs)
コード例 #2
0
class CompanyRegisterForm(forms.Form):

    # FIELDS EMPRESA
    razaosocial = forms.CharField(label='Razão Social:', max_length=100)
    nomefantasia = forms.CharField(label='Nome Fantasia:', max_length=100)
    cnpj = forms.CharField(label='CNPJ:', max_length=20)
    ie = forms.CharField(label='Inscrição Estadual', max_length=45)
    tipo_empresa = forms.ModelChoiceField(TipoEmpresa,
                                          label='Tipo de Empresa:',
                                          widget=forms.Select())

    # FIELDS LOGRADOURO
    cep = forms.CharField(label='CEP:', max_length=10)
    rua = forms.CharField(label='Rua:', max_length=100)
    bairro = forms.CharField(label='Bairro:', max_length=45)
    cidade = forms.CharField(label='Cidade:', max_length=20)
    estado = forms.CharField(label='Estado:', max_length=2)
    pais = forms.CharField(label='País:', max_length=45)

    # FIELDS ENDERECO
    numeroed = forms.IntegerField(label='Numero:')
    complemento = forms.CharField(label='Complemento:', max_length=45)
    pontoreferencia = forms.CharField(label='Ponto de referência:',
                                      max_length=45,
                                      widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        super(CompanyRegisterForm, self).__init__(*args, **kwargs)
        '''
            FIELDS EMPRESA
        '''

        # Razaosocial Fields widget
        self.fields['razaosocial'].widget.attrs['class'] = 'form-control'
        self.fields['razaosocial'].widget.attrs[
            'placeholder'] = 'Digite a Razão Social'

        # Nomefantasia Fields widget
        self.fields['nomefantasia'].widget.attrs['class'] = 'form-control'
        self.fields['nomefantasia'].widget.attrs[
            'placeholder'] = 'Digite o Nome Fantasia'

        # Cnpj Fields widget
        self.fields['cnpj'].widget.attrs['class'] = 'form-control'
        self.fields['cnpj'].widget.attrs[
            'onblur'] = 'get_cnpj_data(this.value)'
        self.fields['cnpj'].widget.attrs[
            'placeholder'] = 'Digite a Razão Social'

        # Ie Fields widget
        self.fields['ie'].widget.attrs['class'] = 'form-control'
        self.fields['ie'].widget.attrs['placeholder'] = 'Inscrição Estadual'

        # Tipo_empresa Fields widget
        self.fields['tipo_empresa'].widget.attrs['class'] = 'form-control'
        self.fields['tipo_empresa'].queryset = TipoEmpresa.objects.all()
        '''
            FIELDS LOGRADOURO
        '''

        # CEP Fields widget
        self.fields['cep'].widget.attrs['class'] = 'form-control'
        self.fields['cep'].widget.attrs['onblur'] = 'get_cep_data(this.value)'
        self.fields['cep'].widget.attrs['placeholder'] = 'Digite o CEP'

        # Rua Fields widget
        self.fields['rua'].widget.attrs['class'] = 'form-control'
        self.fields['rua'].widget.attrs['placeholder'] = 'Digite a rua'

        # Bairro Fields widget
        self.fields['bairro'].widget.attrs['class'] = 'form-control'
        self.fields['bairro'].widget.attrs['placeholder'] = 'Digite o bairro'

        # Cidade Fields widget
        self.fields['cidade'].widget.attrs['class'] = 'form-control'
        self.fields['cidade'].widget.attrs['placeholder'] = 'Digite a cidade'

        # Estado Fields widget
        self.fields['estado'].widget.attrs['class'] = 'form-control'
        self.fields['estado'].widget.attrs['placeholder'] = 'Digite o estado'

        # Pais Fields widget
        self.fields['pais'].widget.attrs['class'] = 'form-control'
        self.fields['pais'].widget.attrs['placeholder'] = 'Digite o pais'
        '''
            FIELDS ENDERECO
        '''

        # Numero Fields widget
        self.fields['numeroed'].widget.attrs['class'] = 'form-control'
        self.fields['numeroed'].widget.attrs['placeholder'] = 'Digite o numero'

        # Complemento Fields widget
        self.fields['complemento'].widget.attrs['class'] = 'form-control'
        self.fields['complemento'].widget.attrs[
            'placeholder'] = 'Digite o complemento'

        # Pontoreferencia Fields widget
        self.fields['pontoreferencia'].widget.attrs['class'] = 'form-control'
        self.fields['pontoreferencia'].widget.attrs[
            'placeholder'] = 'Digite um ponto de referência'

        pass
コード例 #3
0
ファイル: index_codings.py プロジェクト: isususi/amcat
 class options_form(forms.Form):
     job = forms.ModelChoiceField(queryset=CodingJob.objects.all())
コード例 #4
0
class NotificationForm(forms.Form):
    scope = forms.ChoiceField(choices=SCOPE_CHOICES,
                              widget=forms.HiddenInput,
                              required=True)
    project = forms.ModelChoiceField(widget=forms.HiddenInput,
                                     queryset=Project.objects.none(),
                                     required=False)
    component = forms.ModelChoiceField(widget=forms.HiddenInput,
                                       queryset=Component.objects.none(),
                                       required=False)

    def __init__(self, user, show_default, subscriptions, is_active, *args,
                 **kwargs):
        super().__init__(*args, **kwargs)
        self.user = user
        self.is_active = is_active
        self.show_default = show_default
        self.fields["project"].queryset = user.allowed_projects
        self.fields["component"].queryset = Component.objects.filter_access(
            user)
        language_fields = []
        component_fields = []
        for field, notification_cls in self.notification_fields():
            self.fields[field] = forms.ChoiceField(
                label=notification_cls.verbose,
                choices=self.get_choices(notification_cls, show_default),
                required=True,
                initial=self.get_initial(notification_cls, subscriptions,
                                         show_default),
            )
            if notification_cls.filter_languages:
                language_fields.append(field)
            else:
                component_fields.append(field)
        self.helper = FormHelper(self)
        self.helper.disable_csrf = True
        self.helper.form_tag = False
        self.helper.label_class = "col-md-3"
        self.helper.field_class = "col-md-9"
        self.helper.layout = Layout(
            "scope",
            "project",
            "component",
            Fieldset(
                _("Component wide notifications"),
                HTML(escape(self.get_help_component())),
                *component_fields,
            ),
            Fieldset(
                _("Translation notifications"),
                HTML(escape(self.get_help_translation())),
                *language_fields,
            ),
        )

    @staticmethod
    def notification_fields():
        for notification_cls in NOTIFICATIONS:
            yield (f"notify-{notification_cls.get_name()}", notification_cls)

    @staticmethod
    def get_initial(notification_cls, subscriptions, show_default):
        return subscriptions.get(notification_cls.get_name(),
                                 -1 if show_default else 0)

    @staticmethod
    def get_choices(notification_cls, show_default):
        result = []
        if show_default:
            result.append((-1, _("Use default setting")))
        result.extend(notification_cls.get_freq_choices())
        return result

    @cached_property
    def form_params(self):
        if self.is_bound:
            self.is_valid()
            return self.cleaned_data
        return self.initial

    @cached_property
    def form_scope(self):
        return self.form_params.get("scope", SCOPE_WATCHED)

    @cached_property
    def form_project(self):
        return self.form_params.get("project", None)

    @cached_property
    def form_component(self):
        return self.form_params.get("component", None)

    def get_name(self):
        scope = self.form_scope
        if scope == SCOPE_ALL:
            return _("Other projects")
        if scope == SCOPE_WATCHED:
            return _("Watched projects")
        if scope == SCOPE_ADMIN:
            return _("Managed projects")
        if scope == SCOPE_PROJECT:
            return _("Project: {}").format(self.form_project)
        return _("Component: {}").format(self.form_component)

    def get_help_component(self):
        scope = self.form_scope
        if scope == SCOPE_ALL:
            return _("You will receive a notification for every such event"
                     " in non-watched projects.")
        if scope == SCOPE_WATCHED:
            return _("You will receive a notification for every such event"
                     " in your watched projects.")
        if scope == SCOPE_ADMIN:
            return _("You will receive a notification for every such event"
                     " in projects where you have admin permissions.")
        if scope == SCOPE_PROJECT:
            return _(
                "You will receive a notification for every such event in %(project)s."
            ) % {
                "project": self.form_project
            }
        return _(
            "You will receive a notification for every such event in %(component)s."
        ) % {
            "component": self.form_component
        }

    def get_help_translation(self):
        scope = self.form_scope
        if scope == SCOPE_ALL:
            return _(
                "You will only receive these notifications for your translated "
                "languages in non-watched projects.")
        if scope == SCOPE_WATCHED:
            return _(
                "You will only receive these notifications for your translated "
                "languages in your watched projects.")
        if scope == SCOPE_ADMIN:
            return _(
                "You will only receive these notifications for your translated "
                "languages in projects where you have admin permissions.")
        if scope == SCOPE_PROJECT:
            return _("You will only receive these notifications for your"
                     " translated languages in %(project)s.") % {
                         "project": self.form_project
                     }
        return _("You will only receive these notifications for your"
                 " translated languages in %(component)s.") % {
                     "component": self.form_component
                 }

    def save(self):
        # Lookup for this form
        lookup = {
            "scope": self.cleaned_data["scope"],
            "project": self.cleaned_data["project"],
            "component": self.cleaned_data["component"],
        }
        handled = set()
        for field, notification_cls in self.notification_fields():
            frequency = self.cleaned_data[field]
            # We do not store defaults or disabled default subscriptions
            if frequency == "-1" or (frequency == "0"
                                     and not self.show_default):
                continue
            # Create/Get from database
            subscription, created = self.user.subscription_set.get_or_create(
                notification=notification_cls.get_name(),
                defaults={"frequency": frequency},
                **lookup,
            )
            # Update old subscription
            if not created and subscription.frequency != frequency:
                subscription.frequency = frequency
                subscription.save(update_fields=["frequency"])
            handled.add(subscription.pk)
        # Delete stale subscriptions
        self.user.subscription_set.filter(**lookup).exclude(
            pk__in=handled).delete()
コード例 #5
0
class ImportForm(forms.Form):
    def clean(self):
        # If there are validation errors earlier on, don't bother.
        if not ('address_file' in self.cleaned_data and
                        'ignore_errors' in self.cleaned_data and
                        'newsletter' in self.cleaned_data):
            return self.cleaned_data
            # TESTME: Should an error be raised here or not?
            # raise forms.ValidationError(_("No file has been specified."))

        ignore_errors = self.cleaned_data['ignore_errors']
        newsletter = self.cleaned_data['newsletter']

        myfield = self.base_fields['address_file']
        myvalue = myfield.widget.value_from_datadict(
            self.data, self.files, self.add_prefix('address_file'))

        content_type = myvalue.content_type
        allowed_types = ('text/plain', 'application/octet-stream',
                         'text/vcard', 'text/directory', 'text/x-vcard',
                         'application/vnd.ms-excel',
                         'text/comma-separated-values', 'text/csv',
                         'application/csv', 'application/excel',
                         'application/vnd.msexcel', 'text/anytext')
        if content_type not in allowed_types:
            raise forms.ValidationError(_(
                "File type '%s' was not recognized.") % content_type)

        self.addresses = []

        ext = myvalue.name.rsplit('.', 1)[-1].lower()
        if ext == 'vcf':
            self.addresses = parse_vcard(
                myvalue.file, newsletter, ignore_errors)

        elif ext == 'ldif':
            self.addresses = parse_ldif(
                myvalue.file, newsletter, ignore_errors)

        elif ext == 'csv':
            self.addresses = parse_csv(
                myvalue.file, newsletter, ignore_errors)
            print(self.addresses)

        else:
            raise forms.ValidationError(
                _("File extention '%s' was not recognized.") % ext)

        if len(self.addresses) == 0:
            raise forms.ValidationError(
                _("No entries could found in this file."))

        print('cleaned data')
        print(self.cleaned_data)
        return self.cleaned_data

    def get_addresses(self):
        if hasattr(self, 'addresses'):
            # print('el objeto tiene atributo addresses')
            logger.debug('Getting addresses: %s', self.addresses)
            # print(self.addresses)
            return self.addresses
        else:
            return {}

    newsletter = forms.ModelChoiceField(
        label=_("Newsletter"),
        queryset=Newsletter.objects.all(),
        initial=Newsletter.get_default_id())
    address_file = forms.FileField(label=_("Address file"))
    ignore_errors = forms.BooleanField(
        label=_("Ignore non-fatal errors"),
        initial=True, required=False)
コード例 #6
0
ファイル: forms.py プロジェクト: atmospheresnode/ELSA
class InvestigationForm(forms.Form):
    investigation = forms.ModelChoiceField(queryset=Investigation.objects.all(), required=True, help_text="Note: Investigations contain: individual investigations, missions, observing campaigns, or other investigations</br>")
コード例 #7
0
class DatabaseForm(models.ModelForm):
    plan = AdvancedModelChoiceField(
        queryset=Plan.objects.filter(is_active='True'),
        required=False,
        widget=forms.RadioSelect,
        empty_label=None)
    engine = forms.ModelChoiceField(queryset=Engine.objects)
    environment = forms.ModelChoiceField(queryset=Environment.objects)

    class Meta:
        model = Database
        fields = (
            'name',
            'description',
            'project',
            'team',
            'is_in_quarantine',
        )

    def remove_fields_not_in_models(self):
        """remove fields not int models"""
        fields_to_remove = ["plan", "engine", "environment"]
        for field_name in fields_to_remove:
            if field_name in self.fields:
                del self.fields[field_name]

    @classmethod
    def setup_offering_field(cls, form, db_instance):
        form.declared_fields['offering'] = forms.CharField(
            widget=DatabaseOfferingWidget(attrs={
                'readonly': 'readonly',
                'database': db_instance
            }),
            required=False,
            initial=db_instance.offering)

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

        super(DatabaseForm, self).__init__(*args, **kwargs)
        instance = kwargs.get('instance')
        if instance:
            LOG.debug("instance database form found! %s" % instance)
            #remove fields not in models
            self.remove_fields_not_in_models()

        else:
            self.fields['is_in_quarantine'].widget = forms.HiddenInput()

    def clean(self):
        cleaned_data = super(DatabaseForm, self).clean()

        # if there is an instance, that means that we are in a edit page and therefore
        # it should return the default cleaned_data
        if self.instance and self.instance.id:
            return cleaned_data

        # TODO: change model field to blank=False
        if 'team' in cleaned_data:
            team = cleaned_data['team']
            LOG.debug("team: %s" % team)

            if not team:
                LOG.warning("No team specified in database form")
                self._errors["team"] = self.error_class(
                    [_("Team: This field is required.")])

        if not self.is_valid():
            raise forms.ValidationError(self.errors)

        if len(cleaned_data['name']) > 40:
            self._errors["name"] = self.error_class(
                [_("Database name too long")])

        if 'plan' in cleaned_data:
            plan = cleaned_data.get('plan', None)
            if not plan:
                self._errors["plan"] = self.error_class(
                    [_("Plan: This field is required.")])

        if 'project' in cleaned_data:
            project = cleaned_data.get('project', None)
            if not project:
                self._errors["project"] = self.error_class(
                    [_("Project: This field is required.")])

        if 'description' in cleaned_data:
            description = cleaned_data.get('description', None)
            if not description:
                self._errors["description"] = self.error_class(
                    [_("Description: This field is required.")])

        if 'environment' in cleaned_data:
            environment = cleaned_data.get('environment', None)
            if not environment or environment not in plan.environments.all():
                raise forms.ValidationError(
                    _("Invalid plan for selected environment."))

            #validate if the team has available resources
            dbs = team.databases_in_use_for(environment)
            database_alocation_limit = team.database_alocation_limit
            LOG.debug("dbs: %s | type: %s" % (dbs, type(dbs)))
            if (database_alocation_limit != 0
                    and len(dbs) >= database_alocation_limit):
                LOG.warning(
                    "The database alocation limit of %s has been exceeded for the selected team %s => %s"
                    % (database_alocation_limit, team, list(dbs)))
                self._errors["team"] = self.error_class([
                    _("The database alocation limit of %s has been exceeded for the selected team: %s"
                      ) % (database_alocation_limit, list(dbs))
                ])

        #for infra in DatabaseInfra.objects.filter(environment=environment,):
        #   if infra.databases.filter(name=cleaned_data['name']):
        #      self._errors["name"] = self.error_class([_("this name already exists in the selected environment")])

        driver = DriverFactory.get_driver_class(plan.engines[0].name)
        if 'name' in cleaned_data and cleaned_data[
                'name'] in driver.RESERVED_DATABASES_NAME:
            raise forms.ValidationError(
                _("%s is a reserved database name" % cleaned_data['name']))

        if self._errors:
            return cleaned_data

        return cleaned_data

    def save_m2m(self, *args, **kwargs):
        pass
コード例 #8
0
ファイル: forms.py プロジェクト: mpaulvijay/netbox
class PrefixCSVForm(forms.ModelForm):
    vrf = FlexibleModelChoiceField(
        queryset=VRF.objects.all(),
        to_field_name='rd',
        required=False,
        help_text='Route distinguisher of parent VRF (or {ID})',
        error_messages={
            'invalid_choice': 'VRF not found.',
        }
    )
    tenant = forms.ModelChoiceField(
        queryset=Tenant.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name of assigned tenant',
        error_messages={
            'invalid_choice': 'Tenant not found.',
        }
    )
    site = forms.ModelChoiceField(
        queryset=Site.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name of parent site',
        error_messages={
            'invalid_choice': 'Site not found.',
        }
    )
    vlan_group = forms.CharField(
        help_text='Group name of assigned VLAN',
        required=False
    )
    vlan_vid = forms.IntegerField(
        help_text='Numeric ID of assigned VLAN',
        required=False
    )
    status = CSVChoiceField(
        choices=PrefixStatusChoices,
        help_text='Operational status'
    )
    role = forms.ModelChoiceField(
        queryset=Role.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Functional role',
        error_messages={
            'invalid_choice': 'Invalid role.',
        }
    )

    class Meta:
        model = Prefix
        fields = Prefix.csv_headers

    def clean(self):

        super().clean()

        site = self.cleaned_data.get('site')
        vlan_group = self.cleaned_data.get('vlan_group')
        vlan_vid = self.cleaned_data.get('vlan_vid')

        # Validate VLAN
        if vlan_group and vlan_vid:
            try:
                self.instance.vlan = VLAN.objects.get(site=site, group__name=vlan_group, vid=vlan_vid)
            except VLAN.DoesNotExist:
                if site:
                    raise forms.ValidationError("VLAN {} not found in site {} group {}".format(
                        vlan_vid, site, vlan_group
                    ))
                else:
                    raise forms.ValidationError("Global VLAN {} not found in group {}".format(vlan_vid, vlan_group))
            except MultipleObjectsReturned:
                raise forms.ValidationError(
                    "Multiple VLANs with VID {} found in group {}".format(vlan_vid, vlan_group)
                )
        elif vlan_vid:
            try:
                self.instance.vlan = VLAN.objects.get(site=site, group__isnull=True, vid=vlan_vid)
            except VLAN.DoesNotExist:
                if site:
                    raise forms.ValidationError("VLAN {} not found in site {}".format(vlan_vid, site))
                else:
                    raise forms.ValidationError("Global VLAN {} not found".format(vlan_vid))
            except MultipleObjectsReturned:
                raise forms.ValidationError("Multiple VLANs with VID {} found".format(vlan_vid))
コード例 #9
0
ファイル: forms.py プロジェクト: mpaulvijay/netbox
class IPAddressForm(BootstrapMixin, TenancyForm, ReturnURLForm, CustomFieldForm):
    interface = forms.ModelChoiceField(
        queryset=Interface.objects.all(),
        required=False
    )
    nat_site = forms.ModelChoiceField(
        queryset=Site.objects.all(),
        required=False,
        label='Site',
        widget=APISelect(
            api_url="/api/dcim/sites/",
            filter_for={
                'nat_rack': 'site_id',
                'nat_device': 'site_id'
            }
        )
    )
    nat_rack = ChainedModelChoiceField(
        queryset=Rack.objects.all(),
        chains=(
            ('site', 'nat_site'),
        ),
        required=False,
        label='Rack',
        widget=APISelect(
            api_url='/api/dcim/racks/',
            display_field='display_name',
            filter_for={
                'nat_device': 'rack_id'
            },
            attrs={
                'nullable': 'true'
            }
        )
    )
    nat_device = ChainedModelChoiceField(
        queryset=Device.objects.all(),
        chains=(
            ('site', 'nat_site'),
            ('rack', 'nat_rack'),
        ),
        required=False,
        label='Device',
        widget=APISelect(
            api_url='/api/dcim/devices/',
            display_field='display_name',
            filter_for={
                'nat_inside': 'device_id'
            }
        )
    )
    nat_inside = ChainedModelChoiceField(
        queryset=IPAddress.objects.all(),
        chains=(
            ('interface__device', 'nat_device'),
        ),
        required=False,
        label='IP Address',
        widget=APISelect(
            api_url='/api/ipam/ip-addresses/',
            display_field='address'
        )
    )
    primary_for_parent = forms.BooleanField(
        required=False,
        label='Make this the primary IP for the device/VM'
    )
    tags = TagField(
        required=False
    )

    class Meta:
        model = IPAddress
        fields = [
            'address', 'vrf', 'status', 'role', 'dns_name', 'description', 'interface', 'primary_for_parent',
            'nat_site', 'nat_rack', 'nat_inside', 'tenant_group', 'tenant', 'tags',
        ]
        widgets = {
            'status': StaticSelect2(),
            'role': StaticSelect2(),
            'vrf': APISelect(
                api_url="/api/ipam/vrfs/"
            )
        }

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

        # Initialize helper selectors
        instance = kwargs.get('instance')
        initial = kwargs.get('initial', {}).copy()
        if instance and instance.nat_inside and instance.nat_inside.device is not None:
            initial['nat_site'] = instance.nat_inside.device.site
            initial['nat_rack'] = instance.nat_inside.device.rack
            initial['nat_device'] = instance.nat_inside.device
        kwargs['initial'] = initial

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

        self.fields['vrf'].empty_label = 'Global'

        # Limit interface selections to those belonging to the parent device/VM
        if self.instance and self.instance.interface:
            self.fields['interface'].queryset = Interface.objects.filter(
                device=self.instance.interface.device, virtual_machine=self.instance.interface.virtual_machine
            )
        else:
            self.fields['interface'].choices = []

        # Initialize primary_for_parent if IP address is already assigned
        if self.instance.pk and self.instance.interface is not None:
            parent = self.instance.interface.parent
            if (
                self.instance.address.version == 4 and parent.primary_ip4_id == self.instance.pk or
                self.instance.address.version == 6 and parent.primary_ip6_id == self.instance.pk
            ):
                self.initial['primary_for_parent'] = True

    def clean(self):
        super().clean()

        # Primary IP assignment is only available if an interface has been assigned.
        if self.cleaned_data.get('primary_for_parent') and not self.cleaned_data.get('interface'):
            self.add_error(
                'primary_for_parent', "Only IP addresses assigned to an interface can be designated as primary IPs."
            )

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

        ipaddress = super().save(*args, **kwargs)

        # Assign/clear this IPAddress as the primary for the associated Device/VirtualMachine.
        if self.cleaned_data['primary_for_parent']:
            parent = self.cleaned_data['interface'].parent
            if ipaddress.address.version == 4:
                parent.primary_ip4 = ipaddress
            else:
                parent.primary_ip6 = ipaddress
            parent.save()
        elif self.cleaned_data['interface']:
            parent = self.cleaned_data['interface'].parent
            if ipaddress.address.version == 4 and parent.primary_ip4 == ipaddress:
                parent.primary_ip4 = None
                parent.save()
            elif ipaddress.address.version == 6 and parent.primary_ip6 == ipaddress:
                parent.primary_ip6 = None
                parent.save()

        return ipaddress
コード例 #10
0
ファイル: forms.py プロジェクト: mpaulvijay/netbox
class VLANCSVForm(forms.ModelForm):
    site = forms.ModelChoiceField(
        queryset=Site.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name of parent site',
        error_messages={
            'invalid_choice': 'Site not found.',
        }
    )
    group_name = forms.CharField(
        help_text='Name of VLAN group',
        required=False
    )
    tenant = forms.ModelChoiceField(
        queryset=Tenant.objects.all(),
        to_field_name='name',
        required=False,
        help_text='Name of assigned tenant',
        error_messages={
            'invalid_choice': 'Tenant not found.',
        }
    )
    status = CSVChoiceField(
        choices=VLANStatusChoices,
        help_text='Operational status'
    )
    role = forms.ModelChoiceField(
        queryset=Role.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Functional role',
        error_messages={
            'invalid_choice': 'Invalid role.',
        }
    )

    class Meta:
        model = VLAN
        fields = VLAN.csv_headers
        help_texts = {
            'vid': 'Numeric VLAN ID (1-4095)',
            'name': 'VLAN name',
        }

    def clean(self):
        super().clean()

        site = self.cleaned_data.get('site')
        group_name = self.cleaned_data.get('group_name')

        # Validate VLAN group
        if group_name:
            try:
                self.instance.group = VLANGroup.objects.get(site=site, name=group_name)
            except VLANGroup.DoesNotExist:
                if site:
                    raise forms.ValidationError(
                        "VLAN group {} not found for site {}".format(group_name, site)
                    )
                else:
                    raise forms.ValidationError(
                        "Global VLAN group {} not found".format(group_name)
                    )
コード例 #11
0
ファイル: forms.py プロジェクト: mpaulvijay/netbox
class PrefixForm(BootstrapMixin, TenancyForm, CustomFieldForm):
    site = forms.ModelChoiceField(
        queryset=Site.objects.all(),
        required=False,
        label='Site',
        widget=APISelect(
            api_url="/api/dcim/sites/",
            filter_for={
                'vlan_group': 'site_id',
                'vlan': 'site_id',
            },
            attrs={
                'nullable': 'true',
            }
        )
    )
    vlan_group = ChainedModelChoiceField(
        queryset=VLANGroup.objects.all(),
        chains=(
            ('site', 'site'),
        ),
        required=False,
        label='VLAN group',
        widget=APISelect(
            api_url='/api/ipam/vlan-groups/',
            filter_for={
                'vlan': 'group_id'
            },
            attrs={
                'nullable': 'true',
            }
        )
    )
    vlan = ChainedModelChoiceField(
        queryset=VLAN.objects.all(),
        chains=(
            ('site', 'site'),
            ('group', 'vlan_group'),
        ),
        required=False,
        label='VLAN',
        widget=APISelect(
            api_url='/api/ipam/vlans/',
            display_field='display_name'
        )
    )
    tags = TagField(required=False)

    class Meta:
        model = Prefix
        fields = [
            'prefix', 'vrf', 'site', 'vlan', 'status', 'role', 'is_pool', 'description', 'tenant_group', 'tenant',
            'tags',
        ]
        widgets = {
            'vrf': APISelect(
                api_url="/api/ipam/vrfs/"
            ),
            'status': StaticSelect2(),
            'role': APISelect(
                api_url="/api/ipam/roles/"
            )
        }

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

        # Initialize helper selectors
        instance = kwargs.get('instance')
        initial = kwargs.get('initial', {}).copy()
        if instance and instance.vlan is not None:
            initial['vlan_group'] = instance.vlan.group
        kwargs['initial'] = initial

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

        self.fields['vrf'].empty_label = 'Global'
コード例 #12
0
class SalesmanActivateForm(forms.Form):
    salesman = forms.ModelChoiceField(
        queryset=Salesman.objects.filter(user__is_active=False),
        empty_label=None,
        required=True)
コード例 #13
0
class NewMedicineForm(ModelForm):
	vendor = forms.ModelChoiceField(queryset=Vendor.objects.all(), initial=0)
	class Meta:
		model = Medicine
		fields = ['trade_name','generic_name','description','purchasePrice','unit_selling','threshold_value','vendor']
		
コード例 #14
0
class NewJobForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        clients = Contact.objects.filter(contact_type='client')
        staff = Staff.objects.all()
        vehicles = Vehicle.objects.all()
        self.fields['client'].queryset = clients
        self.fields['assigned'].queryset = staff
        self.fields['vehicle'].queryset = vehicles
        if 'client' in self.data:
            try:
                owner_id = int(self.data.get('client'))
                self.fields['vehicle'].queryset = Contact.objects.get(
                    owner_id).vehicle_set.all()
            except (ValueError, TypeError):
                pass  # invalid input; fallback to empty Vehicle queryset

    select_attrs = {'class': 'form-control'}
    input_attrs = {'class': 'form-control'}
    date_attrs = {
        'class': 'form-control',
        'type': 'date',
        'placeholder': 'dd/mm/yyyy'
    }
    job_status_choices = (('pending', 'Pending (Estimate)'),
                          ('confirmed', 'Confirmed (Estimate)'),
                          ('in_progress', 'In progress'), ('done', 'Done'))
    payment_method_choices = (('cash', 'Cash'), ('card', 'Card'), ('mpesa',
                                                                   'M-Pesa'))

    client = forms.ModelChoiceField(queryset=None,
                                    widget=forms.Select(attrs=select_attrs))
    vehicle = forms.ModelChoiceField(queryset=None,
                                     widget=forms.Select(attrs=select_attrs))
    due_start_date = forms.DateField(widget=forms.DateInput(attrs=date_attrs),
                                     required=False)
    due_end_date = forms.DateField(widget=forms.DateInput(attrs=date_attrs),
                                   required=False)
    description = forms.CharField(widget=forms.Textarea(attrs={
        **input_attrs,
        **{
            'rows': 3
        }
    }),
                                  required=False)
    assigned = forms.ModelChoiceField(required=False,
                                      queryset=None,
                                      widget=forms.Select(attrs=select_attrs))
    charged = forms.CharField(widget=forms.NumberInput(attrs={
        **input_attrs,
        **{
            'value': 0
        }
    }),
                              required=False)
    status = forms.ChoiceField(choices=job_status_choices,
                               widget=forms.Select(attrs=select_attrs))
    payment_method = forms.ChoiceField(choices=payment_method_choices,
                                       widget=forms.Select(attrs=select_attrs))

    def clean(self):
        start_date = self.cleaned_data.get('due_start_date')
        end_date = self.cleaned_data.get('due_end_date')
        if not (start_date and end_date):
            return self.cleaned_data
        if start_date > end_date:
            raise forms.ValidationError(
                'Due start date can not be later than due end date.')
コード例 #15
0
ファイル: forms.py プロジェクト: atmospheresnode/ELSA
class TelescopeForm(forms.Form):
    telescope = forms.ModelChoiceField(queryset=Telescope.objects.all(), required=True)
コード例 #16
0
ファイル: forms.py プロジェクト: mpaulvijay/netbox
class IPAddressCSVForm(forms.ModelForm):
    vrf = FlexibleModelChoiceField(
        queryset=VRF.objects.all(),
        to_field_name='rd',
        required=False,
        help_text='Route distinguisher of parent VRF (or {ID})',
        error_messages={
            'invalid_choice': 'VRF not found.',
        }
    )
    tenant = forms.ModelChoiceField(
        queryset=Tenant.objects.all(),
        to_field_name='name',
        required=False,
        help_text='Name of the assigned tenant',
        error_messages={
            'invalid_choice': 'Tenant not found.',
        }
    )
    status = CSVChoiceField(
        choices=IPAddressStatusChoices,
        help_text='Operational status'
    )
    role = CSVChoiceField(
        choices=IPAddressRoleChoices,
        required=False,
        help_text='Functional role'
    )
    device = FlexibleModelChoiceField(
        queryset=Device.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name or ID of assigned device',
        error_messages={
            'invalid_choice': 'Device not found.',
        }
    )
    virtual_machine = forms.ModelChoiceField(
        queryset=VirtualMachine.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name of assigned virtual machine',
        error_messages={
            'invalid_choice': 'Virtual machine not found.',
        }
    )
    interface_name = forms.CharField(
        help_text='Name of assigned interface',
        required=False
    )
    is_primary = forms.BooleanField(
        help_text='Make this the primary IP for the assigned device',
        required=False
    )

    class Meta:
        model = IPAddress
        fields = IPAddress.csv_headers

    def clean(self):
        super().clean()

        device = self.cleaned_data.get('device')
        virtual_machine = self.cleaned_data.get('virtual_machine')
        interface_name = self.cleaned_data.get('interface_name')
        is_primary = self.cleaned_data.get('is_primary')

        # Validate interface
        if interface_name and device:
            try:
                self.instance.interface = Interface.objects.get(device=device, name=interface_name)
            except Interface.DoesNotExist:
                raise forms.ValidationError("Invalid interface {} for device {}".format(
                    interface_name, device
                ))
        elif interface_name and virtual_machine:
            try:
                self.instance.interface = Interface.objects.get(virtual_machine=virtual_machine, name=interface_name)
            except Interface.DoesNotExist:
                raise forms.ValidationError("Invalid interface {} for virtual machine {}".format(
                    interface_name, virtual_machine
                ))
        elif interface_name:
            raise forms.ValidationError("Interface given ({}) but parent device/virtual machine not specified".format(
                interface_name
            ))
        elif device:
            raise forms.ValidationError("Device specified ({}) but interface missing".format(device))
        elif virtual_machine:
            raise forms.ValidationError("Virtual machine specified ({}) but interface missing".format(virtual_machine))

        # Validate is_primary
        if is_primary and not device and not virtual_machine:
            raise forms.ValidationError("No device or virtual machine specified; cannot set as primary IP")

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

        # Set interface
        if self.cleaned_data['device'] and self.cleaned_data['interface_name']:
            self.instance.interface = Interface.objects.get(
                device=self.cleaned_data['device'],
                name=self.cleaned_data['interface_name']
            )
        elif self.cleaned_data['virtual_machine'] and self.cleaned_data['interface_name']:
            self.instance.interface = Interface.objects.get(
                virtual_machine=self.cleaned_data['virtual_machine'],
                name=self.cleaned_data['interface_name']
            )

        ipaddress = super().save(*args, **kwargs)

        # Set as primary for device/VM
        if self.cleaned_data['is_primary']:
            parent = self.cleaned_data['device'] or self.cleaned_data['virtual_machine']
            if self.instance.address.version == 4:
                parent.primary_ip4 = ipaddress
            elif self.instance.address.version == 6:
                parent.primary_ip6 = ipaddress
            parent.save()

        return ipaddress
コード例 #17
0
ファイル: forms.py プロジェクト: atmospheresnode/ELSA
 def __init__(self, *args, **kwargs):
     self.pk_fac = kwargs.pop('pk_fac')
     super(FacilityInstrumentForm,self).__init__(*args, **kwargs)
     self.fields['instrument'] = forms.ModelChoiceField(queryset=Instrument.objects.filter(facility=self.pk_fac), required=True)
コード例 #18
0
ファイル: forms.py プロジェクト: beatriz-soares/sosgirls
class FiltroDepoimentoForm(forms.Form):
    tipo = forms.ModelChoiceField(TipoDepoimentos.objects.all(),
                                  required=False)
コード例 #19
0
ファイル: forms.py プロジェクト: atmospheresnode/ELSA
 def __init__(self, *args, **kwargs):
     self.pk_ins = kwargs.pop('pk_ins')
     super(InstrumentForm,self).__init__(*args, **kwargs)
     self.fields['instrument'] = forms.ModelChoiceField(queryset=Instrument.objects.filter(instrument_host=self.pk_ins), required=True)
コード例 #20
0
    def __init__(self, *args, **kwargs):
        self.event = kwargs['event']
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

        self.fields['category'].queryset = self.instance.event.categories.all()
        self.fields['category'].widget = Select2(
            attrs={
                'data-model-select2':
                'generic',
                'data-select2-url':
                reverse('control:event.items.categories.select2',
                        kwargs={
                            'event': self.instance.event.slug,
                            'organizer': self.instance.event.organizer.slug,
                        }),
                'data-placeholder':
                _('No category'),
            })
        self.fields['category'].widget.choices = self.fields[
            'category'].choices

        self.fields['tax_rule'].queryset = self.instance.event.tax_rules.all()
        change_decimal_field(self.fields['default_price'],
                             self.instance.event.currency)
        self.fields['tax_rule'].empty_label = _('No taxation')
        self.fields['copy_from'] = forms.ModelChoiceField(
            label=_("Copy product information"),
            queryset=self.event.items.all(),
            widget=forms.Select,
            empty_label=_('Do not copy'),
            required=False)
        if self.event.tax_rules.exists():
            self.fields['tax_rule'].required = True

        if not self.event.has_subevents:
            choices = [(self.NONE, _("Do not add to a quota now")),
                       (self.EXISTING, _("Add product to an existing quota")),
                       (self.NEW, _("Create a new quota for this product"))]
            if not self.event.quotas.exists():
                choices.remove(choices[1])

            self.fields['quota_option'] = forms.ChoiceField(
                label=_("Quota options"),
                widget=forms.RadioSelect,
                choices=choices,
                initial=self.NONE,
                required=False)

            self.fields['quota_add_existing'] = forms.ModelChoiceField(
                label=_("Add to existing quota"),
                widget=forms.Select(),
                queryset=self.instance.event.quotas.all(),
                required=False)

            self.fields['quota_add_new_name'] = forms.CharField(
                label=_("Name"),
                max_length=200,
                widget=forms.TextInput(
                    attrs={'placeholder': _("New quota name")}),
                required=False)

            self.fields['quota_add_new_size'] = forms.IntegerField(
                min_value=0,
                label=_("Size"),
                widget=forms.TextInput(
                    attrs={'placeholder': _("Number of tickets")}),
                help_text=_("Leave empty for an unlimited number of tickets."),
                required=False)
コード例 #21
0
class CloneDatabaseForm(forms.Form):
    database_clone = forms.CharField(label=u'Destination database',
                                     max_length=64,
                                     required=True)
    environment = forms.ModelChoiceField(
        queryset=Environment.objects,
        widget=forms.Select(attrs={'class': 'environment'}),
        required='True',
    )
    engine = forms.CharField(widget=forms.HiddenInput(), )
    origin_database_id = forms.CharField(widget=forms.HiddenInput())
    old_plan = forms.CharField(widget=forms.HiddenInput())

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

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

        if 'initial' in kwargs:
            instance = Database.objects.get(
                id=kwargs['initial']['origin_database_id'])
        elif 'origin_database_id' in self.data:
            instance = Database.objects.get(id=self.data['origin_database_id'])

        if instance:
            LOG.debug("instance database form found! %s" % instance)
            self.define_engine_field(database=instance)
            self.define_available_plans(database=instance)

        self.initial['old_plan'] = instance.plan.id

    def define_engine_field(self, database):
        self.initial['engine'] = database.infra.engine.engine_type.id

    def define_available_plans(self, database):
        self.fields['plan'] = forms.ModelChoiceField(
            queryset=Plan.objects.filter(
                engine_type__name=database.infra.engine.name, is_active=True),
            widget=forms.Select(attrs={'class': 'plan'}),
            required=True,
        )

    def clean(self):
        cleaned_data = super(CloneDatabaseForm, self).clean()
        if 'database_clone' in cleaned_data:

            origindatabase = Database.objects.get(
                pk=cleaned_data['origin_database_id'])

            #for infra in DatabaseInfra.objects.filter(environment=origindatabase.environment,plan=origindatabase.plan):
            #    if infra.databases.filter(name=cleaned_data['database_clone']):
            #        self._errors["database_clone"] = self.error_class([_("this name already exists in the selected environment")])

            if len(cleaned_data['database_clone']) > 40:
                self._errors["database_clone"] = self.error_class(
                    [_("Database name too long")])

            dbs = origindatabase.team.databases_in_use_for(
                origindatabase.environment)
            database_alocation_limit = origindatabase.team.database_alocation_limit
            LOG.debug("dbs: %s | type: %s" % (dbs, type(dbs)))
            if (database_alocation_limit != 0
                    and len(dbs) >= database_alocation_limit):
                LOG.warning(
                    "The database alocation limit of %s has been exceeded for the team: %s => %s"
                    %
                    (database_alocation_limit, origindatabase.team, list(dbs)))
                raise forms.ValidationError([
                    _("The database alocation limit of %s has been exceeded for the team:  %s => %s"
                      ) %
                    (database_alocation_limit, origindatabase.team, list(dbs))
                ])

            driver = DriverFactory.get_driver_class(
                origindatabase.plan.engines[0].name)
            if cleaned_data[
                    'database_clone'] in driver.RESERVED_DATABASES_NAME:
                raise forms.ValidationError(
                    _("%s is a reserved database name" %
                      cleaned_data['database_clone']))

            if self._errors:
                return cleaned_data

        return cleaned_data
コード例 #22
0
class RunCloneForm(BaseRunForm):
    build = forms.ModelChoiceField(
        label='Build',
        queryset=Build.objects.none(),
        empty_label=None,
    )
コード例 #23
0
class GroupRemoveForm(forms.Form):
    remove_group = forms.ModelChoiceField(queryset=Group.objects.all(),
                                          required=True)
コード例 #24
0
ファイル: forms.py プロジェクト: arkryonia/kuiqblog
class PostForm(forms.ModelForm):
	category = forms.ModelChoiceField(queryset=Category.objects.all())
	class Meta:
		model = Post
		fields = ['title', 'category', 'image', 'image_alt', 'is_public', 'content']
コード例 #25
0
class UserRegisterForm(forms.Form):

    # FIELDS USUARIO
    nome = forms.CharField(label='Nome:', max_length=45)
    sobrenome = forms.CharField(label='Sobrenome:', max_length=45)
    email = forms.CharField(label='Email:', max_length=75)
    password = forms.CharField(label='Senha', widget=forms.PasswordInput)
    repetir_password = forms.CharField(label='Confirmação de Senha',
                                       widget=forms.PasswordInput)
    tipo_usuario = forms.ModelChoiceField(TipoUsuario,
                                          label='Tipo de Usuário:',
                                          widget=forms.Select())
    genero = forms.ModelChoiceField(Genero,
                                    label='Genero:',
                                    widget=forms.Select())
    data_nascimento = forms.DateField(
        label='Data de Nascimento:', input_formats=settings.DATE_INPUT_FORMATS)
    cpf = forms.CharField(label='CPF:', max_length=14)
    rg = forms.CharField(label='RG:', max_length=12)
    orgaoemissor = forms.CharField(label='Orgão Emissor:', max_length=45)
    foto = forms.ImageField(label='Foto:', required=False)

    # FIELDS LOGRADOURO
    cep = forms.CharField(label='CEP:', max_length=10)
    rua = forms.CharField(label='Rua:', max_length=100)
    bairro = forms.CharField(label='Bairro:', max_length=45)
    cidade = forms.CharField(label='Cidade:', max_length=20)
    estado = forms.CharField(label='Estado:', max_length=2)
    pais = forms.CharField(label='País:', max_length=45)

    # FIELDS ENDERECO
    numero = forms.IntegerField(label='Numero:')
    complemento = forms.CharField(label='Complemento:', max_length=45)
    pontoreferencia = forms.CharField(label='Ponto de referência:',
                                      max_length=45,
                                      widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        super(UserRegisterForm, self).__init__(*args, **kwargs)
        '''
            FIELDS USUARIO
        '''

        # Frist Name Fields widget
        self.fields['nome'].widget.attrs['class'] = 'form-control'
        self.fields['nome'].widget.attrs['placeholder'] = 'Digite o nome'

        # Last Name Fields widget
        self.fields['sobrenome'].widget.attrs['class'] = 'form-control'
        self.fields['sobrenome'].widget.attrs[
            'placeholder'] = 'Digite o sobrenome'

        # Email Fields widget
        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['placeholder'] = 'Digite o email'

        # Password Fields widget
        self.fields['password'].widget.attrs['class'] = 'form-control'
        self.fields['password'].widget.attrs[
            'placeholder'] = 'Digite uma senha'

        # Repetir_senha Fields widget
        self.fields['repetir_password'].widget.attrs['class'] = 'form-control'
        self.fields['repetir_password'].widget.attrs[
            'placeholder'] = 'Repita a senha'

        # Tipo_usuario Fields widget
        self.fields['tipo_usuario'].widget.attrs['class'] = 'form-control'
        self.fields['tipo_usuario'].queryset = TipoUsuario.objects.all()

        # Genero Fields widget
        self.fields['genero'].widget.attrs['class'] = 'form-control'
        self.fields['genero'].queryset = Genero.objects.all()

        # Data Nascimento Fields widget
        self.fields['data_nascimento'].widget.attrs['class'] = 'form-control'
        self.fields['data_nascimento'].widget.attrs[
            'placeholder'] = 'Digite a data de nascimento'

        # CPF Fields widget
        self.fields['cpf'].widget.attrs['class'] = 'form-control'
        self.fields['cpf'].widget.attrs['placeholder'] = 'Digite o CPF'

        # RG Fields widget
        self.fields['rg'].widget.attrs['class'] = 'form-control'
        self.fields['rg'].widget.attrs['placeholder'] = 'Digite o RG'

        # Orgao Emissor Fields widget
        self.fields['orgaoemissor'].widget.attrs['class'] = 'form-control'
        self.fields['orgaoemissor'].widget.attrs[
            'placeholder'] = 'Digite o Orgao Emissor'

        # Foto Fields widget
        self.fields['foto'].widget.attrs['class'] = 'form-control'
        self.fields['foto'].widget.attrs['placeholder'] = 'Escolha uma foto'
        '''
            FIELDS LOGRADOURO
        '''

        # CEP Fields widget
        self.fields['cep'].widget.attrs['class'] = 'form-control'
        self.fields['cep'].widget.attrs['onblur'] = 'get_cep_data(this.value)'
        self.fields['cep'].widget.attrs['placeholder'] = 'Digite o CEP'

        # Rua Fields widget
        self.fields['rua'].widget.attrs['class'] = 'form-control'
        self.fields['rua'].widget.attrs['placeholder'] = 'Digite a rua'

        # Bairro Fields widget
        self.fields['bairro'].widget.attrs['class'] = 'form-control'
        self.fields['bairro'].widget.attrs['placeholder'] = 'Digite o bairro'

        # Cidade Fields widget
        self.fields['cidade'].widget.attrs['class'] = 'form-control'
        self.fields['cidade'].widget.attrs['placeholder'] = 'Digite a cidade'

        # Estado Fields widget
        self.fields['estado'].widget.attrs['class'] = 'form-control'
        self.fields['estado'].widget.attrs['placeholder'] = 'Digite o estado'

        # Pais Fields widget
        self.fields['pais'].widget.attrs['class'] = 'form-control'
        self.fields['pais'].widget.attrs['placeholder'] = 'Digite o pais'
        '''
            FIELDS ENDERECO
        '''

        # Numero Fields widget
        self.fields['numero'].widget.attrs['class'] = 'form-control'
        self.fields['numero'].widget.attrs['placeholder'] = 'Digite o numero'

        # Complemento Fields widget
        self.fields['complemento'].widget.attrs['class'] = 'form-control'
        self.fields['complemento'].widget.attrs[
            'placeholder'] = 'Digite o complemento'

        # Pontoreferencia Fields widget
        self.fields['pontoreferencia'].widget.attrs['class'] = 'form-control'
        self.fields['pontoreferencia'].widget.attrs[
            'placeholder'] = 'Digite um ponto de referência'

        pass
コード例 #26
0
class DatabaseForm(models.ModelForm):
    environment = forms.ModelChoiceField(queryset=Environment.objects)
    engine = forms.ModelChoiceField(queryset=Engine.objects)
    plan = AdvancedModelChoiceField(
        queryset=Plan.objects.filter(is_active='True'),
        required=False,
        widget=forms.RadioSelect,
        empty_label=None)

    class Meta:
        model = Database
        fields = [
            'name', 'description', 'project', 'environment', 'engine', 'team',
            'subscribe_to_email_events', 'is_in_quarantine', 'plan'
        ]

    def __init__(self, *args, **kwargs):
        super(DatabaseForm, self).__init__(*args, **kwargs)
        self.fields['is_in_quarantine'].widget = forms.HiddenInput()

    def _validate_description(self, cleaned_data):
        if 'description' in cleaned_data:
            if not cleaned_data.get('description', None):
                self._errors["description"] = self.error_class(
                    [_("Description: This field is required.")])

    def _validate_project(self, cleaned_data):
        if 'project' in cleaned_data:
            if not cleaned_data.get('project', None):
                self._errors["project"] = self.error_class(
                    [_("Project: This field is required.")])

    def _validate_team(self, cleaned_data):
        if 'team' in cleaned_data:
            if not cleaned_data['team']:
                LOG.warning("No team specified in database form")
                self._errors["team"] = self.error_class(
                    [_("Team: This field is required.")])

    def _validate_team_resources(self, cleaned_data):
        team = cleaned_data['team']

        if team:
            dbs = team.databases_in_use_for(cleaned_data['environment'])
            database_alocation_limit = team.database_alocation_limit
            LOG.debug("dbs: %s | type: %s" % (dbs, type(dbs)))

            if (database_alocation_limit != 0
                    and len(dbs) >= database_alocation_limit):
                LOG.warning(
                    "The database alocation limit of %s has been exceeded for the selected team %s => %s"
                    % (database_alocation_limit, team, list(dbs)))
                self._errors["team"] = self.error_class([
                    _("The database alocation limit of %s has been exceeded for the selected team: %s"
                      ) % (database_alocation_limit, list(dbs))
                ])

    def _validate_name(self, cleaned_data):
        if len(cleaned_data['name']) > 40:
            self._errors["name"] = self.error_class(
                [_("Database name too long")])

        plan = cleaned_data['plan']

        class_path = plan.replication_topology.class_path
        driver_name = get_replication_topology_instance(class_path).driver_name
        driver = DriverFactory.get_driver_class(driver_name)

        if cleaned_data['name'] in driver.RESERVED_DATABASES_NAME:
            raise forms.ValidationError(
                _("%s is a reserved database name" % cleaned_data['name']))

    def clean(self):
        cleaned_data = super(DatabaseForm, self).clean()

        if not self.is_valid():
            raise forms.ValidationError(self.errors)

        if 'plan' in cleaned_data:
            plan = cleaned_data.get('plan', None)
            if not plan:
                self._errors["plan"] = self.error_class(
                    [_("Plan: This field is required.")])

        self._validate_name(cleaned_data)
        self._validate_project(cleaned_data)
        self._validate_description(cleaned_data)
        self._validate_team(cleaned_data)

        if 'environment' in cleaned_data:
            environment = cleaned_data.get('environment', None)
            database_name = cleaned_data.get('name', None)
            if not environment or environment not in plan.environments.all():
                raise forms.ValidationError(
                    _("Invalid plan for selected environment."))

            if Database.objects.filter(name=database_name,
                                       environment__name=environment):
                self._errors["name"] = self.error_class([
                    _("this name already exists in the selected environment")
                ])
                del cleaned_data["name"]

        self._validate_team_resources(cleaned_data)
        if database_name_evironment_constraint(database_name,
                                               environment.name):
            raise forms.ValidationError(
                _('%s already exists in production!') % database_name)

        if self._errors:
            return cleaned_data

        return cleaned_data
コード例 #27
0
ファイル: forms.py プロジェクト: chrisdavidmills/zamboni
class UpsellForm(happyforms.Form):
    price = forms.ModelChoiceField(queryset=Price.objects.active(),
                                   label=_lazy(u'App Price'),
                                   empty_label=None,
                                   required=True)
    make_public = forms.TypedChoiceField(choices=APP_PUBLIC_CHOICES,
                                         widget=forms.RadioSelect(),
                                         label=_lazy(
                                             u'When should your app be '
                                             'made available for sale?'),
                                         coerce=int,
                                         required=False)
    free = AddonChoiceField(
        queryset=Addon.objects.none(),
        required=False,
        empty_label='',
        # L10n: "App" is a paid version of this app. "from" is this app.
        label=_lazy(u'App to upgrade from'),
        widget=forms.Select())

    def __init__(self, *args, **kw):
        self.extra = kw.pop('extra')
        self.request = kw.pop('request')
        self.addon = self.extra['addon']

        if 'initial' not in kw:
            kw['initial'] = {}

        kw['initial']['make_public'] = amo.PUBLIC_IMMEDIATELY
        if self.addon.premium:
            kw['initial']['price'] = self.addon.premium.price

        super(UpsellForm, self).__init__(*args, **kw)
        self.fields['free'].queryset = (self.extra['amo_user'].addons.exclude(
            pk=self.addon.pk).filter(premium_type__in=amo.ADDON_FREES,
                                     status__in=amo.VALID_STATUSES,
                                     type=self.addon.type))

        if len(self.fields['price'].choices) > 1:
            # Tier 0 (Free) should not be the default selection.
            self.initial['price'] = (Price.objects.active().exclude(
                price='0.00')[0])

    def clean_make_public(self):
        return (amo.PUBLIC_WAIT
                if self.cleaned_data.get('make_public') else None)

    def save(self):
        if 'price' in self.cleaned_data:
            premium = self.addon.premium
            if not premium:
                premium = AddonPremium()
                premium.addon = self.addon
            premium.price = self.cleaned_data['price']
            premium.save()

        upsell = self.addon.upsold
        if self.cleaned_data['free']:

            # Check if this app was already a premium version for another app.
            if upsell and upsell.free != self.cleaned_data['free']:
                upsell.delete()

            if not upsell:
                upsell = AddonUpsell(premium=self.addon)
            upsell.free = self.cleaned_data['free']
            upsell.save()
        elif upsell:
            upsell.delete()

        self.addon.update(make_public=self.cleaned_data['make_public'])
コード例 #28
0
ファイル: forms.py プロジェクト: atmospheresnode/ELSA
class FacilityForm(forms.Form):
    facility = forms.ModelChoiceField(queryset=Facility.objects.all(), required=True)
コード例 #29
0
ファイル: forms.py プロジェクト: josuechavarria/acuerdos
class AcuerdoPrebasicaForm(ModelForm):
    class Meta:
        model = acuerdo_prebasica
        exclude = ('plaza_disponible', 'estructura_plaza',
                   'estructura_presupuestaria', 'usuario_creador',
                   'fecha_creacion', 'usuario_modificador',
                   'fecha_modificacion')

    movimiento = forms.ModelChoiceField(
        queryset=subtipos_acuerdos.objects.all(),
        widget=forms.Select(attrs={
            'class': 'width-40  chosen-select',
            'required': 'required'
        }))
    accion = forms.CharField(
        label="Acción #",
        widget=forms.TextInput(
            attrs={
                'size': '10',
                'required': 'required',
                'pattern': '[0-9]{4,4}',
                'title': 'El número de acción debe tener 4 dígitos.'
            }))
    nacuerdo = forms.CharField(
        label="Acuerdo #",
        widget=forms.TextInput(
            attrs={
                'size': '23',
                'required': 'required',
                'pattern':
                '[0-9]{4}[\-]{1}[A-Z]{4}[\-]{1}[0-9]{2}[\-]{1}[0-9]{4}',
                'title': 'El número de acuerdo tiene un formato inválido.'
            }))
    fecha = forms.CharField(label="Fecha parámetro",
                            widget=forms.TextInput(
                                attrs={
                                    'required': 'required',
                                    'class': 'form-control date-picker',
                                    'data-date-format': 'yyyy-mm-dd'
                                }))
    vigencia_desde = forms.DateField(
        label="Vigencia desde el",
        widget=forms.DateInput(
            attrs={
                'required': 'required',
                'class': 'form-control date-picker',
                'data-date-format': 'yyyy-mm-dd'
            }))
    vigencia_hasta = forms.DateField(
        label="Hasta",
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'form-control date-picker',
            'data-date-format': 'yyyy-mm-dd'
        }))
    nombres_docente = forms.CharField(
        label="Nombres",
        widget=forms.TextInput(
            attrs={
                'size': '30',
                'readonly': 'readonly',
                'required': 'required',
                'pattern': '[a-zA-Z]{3,45}',
                'title': 'El nombre del docente no es permitido.'
            }))
    apellidos_docente = forms.CharField(
        label="Apellidos",
        widget=forms.TextInput(
            attrs={
                'size': '30',
                'readonly': 'readonly',
                'required': 'required',
                'pattern': '[a-zA-Z]{3,45}',
                'title': 'El nombre del docente no es permitido.'
            }))
    identidad_docente = forms.CharField(
        label="Identidad",
        widget=forms.TextInput(
            attrs={
                'class':
                'form-control',
                'size':
                '18',
                'required':
                'required',
                'pattern':
                '[0-9]{13,13}',
                'title':
                'El número de identidad debe ser numérico y de 13 dígitos.'
            }))
    sexo_docente = forms.CharField(
        label="Género",
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'size': '18',
                'readonly': 'readonly',
                'required': 'required',
                'pattern': '[A-Z]{9,9}',
                'title': 'El género no puede exceder de 9 letras.'
            }))
    clave_escalafon_docente = forms.CharField(
        label="Clave Escalafon",
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'size': '18',
                'required': 'required',
                'pattern': '[a-zA-Z]{2,4}[\s-]{0,1}[0-9]{1,6}',
                'title': 'La clave de escalafon tiene un formato inválido.'
            }))
    fecha_nacimiento_docente = forms.CharField(
        label="Fecha Nacimiento",
        widget=forms.TextInput(
            attrs={
                'required': 'required',
                'readonly': 'readonly',
                'class': 'form-control date-picker',
                'data-date-format': 'yyyy-mm-dd'
            }))
    colegio1 = forms.ModelChoiceField(
        queryset=colegios_magisteriales.objects.all(),
        widget=forms.Select(attrs={'required': 'required'}))
    departamento = forms.ModelChoiceField(queryset=departamento.objects.all())
    municipio = forms.ModelChoiceField(queryset=municipio.objects.all())
    aldea = forms.ModelChoiceField(queryset=aldea.objects.all())
    cargo = forms.ModelChoiceField(queryset=cargos.objects.all())
    estado = forms.ModelChoiceField(queryset=estados_acuerdo.objects.filter(
        pk=1))
    nombre_centro = forms.CharField(
        label="Escuela ",
        widget=forms.TextInput(attrs={
            'size': '55',
            'required': 'required',
            'readonly': 'readonly'
        }))

    def __init__(self, codigo_departamento, codigo_municipio, codigo_aldea,
                 cargo, *args, **kwargs):
        super(AcuerdoPrebasicaForm, self).__init__(*args, **kwargs)

        if codigo_departamento:
            self.fields['departamento'].queryset = departamento.objects.filter(
                codigo_departamento=codigo_departamento)
        if codigo_municipio and codigo_departamento:
            self.fields['municipio'].queryset = municipio.objects.filter(
                departamento__codigo_departamento=codigo_departamento,
                codigo_municipio=codigo_municipio)
        if codigo_aldea and codigo_municipio and codigo_departamento:
            self.fields['aldea'].queryset = aldea.objects.filter(
                codigo_departamento=codigo_departamento,
                codigo_municipio=codigo_municipio,
                codigo_aldea=codigo_aldea)
        if cargo:
            self.fields['cargo'].queryset = cargos.objects.filter(pk=cargo)
コード例 #30
0
class TodoForm(forms.ModelForm):
    short_desc = forms.CharField(widget=forms.TextInput(
        attrs={'autocomplete': 'off'}))
    group = forms.ModelChoiceField(queryset=Group.objects.none(),
                                   required=False)
    assigned_to = forms.ModelChoiceField(queryset=Resource.objects.none(),
                                         required=False)
    created_by = forms.CharField(disabled=True, required=False)
    context_id = forms.ModelChoiceField(
        queryset=Context.objects.all(),
        to_field_name='context_id',
        required=False,
        widget=autocomplete.ModelSelect2(url='context-autocomplete'))
    todo_type = forms.ModelChoiceField(
        queryset=TodoType.objects.all().order_by('name'),
        to_field_name='code',
        required=False)
    status = forms.ModelChoiceField(
        queryset=TodoStatus.objects.all().order_by('name'),
        to_field_name='code',
        required=False)
    start_date = forms.DateField(input_formats=['%d-%b-%Y'],
                                 label='Start Date',
                                 required=False,
                                 widget=forms.DateInput(format='%d-%b-%Y',
                                                        attrs={
                                                            'autocomplete':
                                                            'off',
                                                            'placeholder':
                                                            'Select a date',
                                                            'class':
                                                            'datepicker'
                                                        }))
    end_date = forms.DateField(input_formats=['%d-%b-%Y'],
                               label='End Date',
                               required=False,
                               widget=forms.DateInput(format='%d-%b-%Y',
                                                      attrs={
                                                          'autocomplete':
                                                          'off',
                                                          'placeholder':
                                                          'Select a date',
                                                          'class': 'datepicker'
                                                      }))

    class Meta:
        model = Todo
        fields = [
            'assigned_to',
            'group',
            'context_id',
            'todo_type',
            'short_desc',
            'status',
            'effort_type',
            'effort',
            'start_date',
            'end_date',
        ]

    def clean(self):
        #		print ("Calling Clean Start date --> (1)")
        start_date = self.cleaned_data['start_date']
        end_date = self.cleaned_data['end_date']
        if start_date and end_date and end_date < start_date:
            raise forms.ValidationError(
                'End Date cannot be before Start Date.')


#		print ("Calling Clean Start date --> (2)",start_date)
        super(TodoForm, self).clean()

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

        self.helper = FormHelper()
        self.fields['group'].queryset = Group.objects.filter(
            user=user).all().order_by("name")
        self.fields['assigned_to'].queryset = Resource.objects.filter(
            user__in=User.objects.filter(groups__in=Group.objects.filter(
                user=user))).order_by("res_name")
        formAction = None
        if (mode == 'delete'):
            formAction = Submit('save', 'Delete', css_class='btn btn-danger')
        elif (mode == 'close'):
            formAction = Submit('save',
                                'Complete',
                                css_class='btn btn-success')
        elif (mode == 'copyas'):
            formAction = Submit('save', 'Copy', css_class='btn btn-info')
        else:
            formAction = Submit('save', 'Save', css_class='btn btn-primary')

        self.helper.layout = Layout(
            Row(Column('short_desc', css_class='form-group col-md-12 mb-0'),
                css_class='form-row'),
            Row(Column('context_id', css_class='form-group col-md-12 mb-0'),
                css_class='form-row'),
            Row(Column('group', css_class='form-group col-md-4 mb-0'),
                Column('assigned_to', css_class='form-group col-md-5 mb-0'),
                Column('status', css_class='form-group col-md-3 mb-0'),
                css_class='form-row'),
            Row(Column('todo_type', css_class='form-group col-md-4 mb-0'),
                Column('effort_type', css_class='form-group col-md-4 mb-0'),
                Column('effort', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'),
            Row(Column('start_date', css_class='form-group col-md-4 mb-0'),
                Column('end_date', css_class='form-group col-md-4 mb-0'),
                Column('created_by', css_class='form-group col-md-4 mb-0'),
                css_class='form-row'),
            Row(
                Column(
                    FormActions(
                        formAction,
                        HTML(
                            '<a class="btn btn-warning" href={% url "todo_index" %}>Cancel</a>'
                        ),
                        #            			Button( 'cancel', 'Cancel', css_class="btn btn-md btn-default",data_dismiss="modal")
                    ),
                    css_class='form-group col-md-12 mb-0'),
                css_class='form-row'))