Example #1
0
class ObraForm(forms.Form):
    usuario = "postgres"
    senha = "admin123"

    BD = ConexaoBD("localhost", "SistemaBiblioteca", usuario, senha)

    titulo = forms.CharField(label='Título', max_length=100)
    isbn = forms.CharField(label='ISBN', max_length=100)
    ano_publicacao = forms.DateField(label="Ano de publicação")

    autor = BD.select("Autor", ["id_autor", "nome"], nome_atributo=False)
    id_autor = forms.ChoiceField(label='Autor',
                                 widget=forms.Select,
                                 choices=autor)

    editoras = BD.select("Editora", ["id_editora", "nome"],
                         nome_atributo=False)
    id_editora = forms.ChoiceField(label='Editora',
                                   widget=forms.Select,
                                   choices=editoras)

    generos = BD.select("Genero", ["id_genero", "nome"], nome_atributo=False)
    id_genero = forms.MultipleChoiceField(
        required=True,
        widget=forms.CheckboxSelectMultiple,
        choices=generos,
        label="Gênero",
    )

    palavra_chave = BD.select("Palavras_chaves", ["id_palavra_chave", "nome"],
                              nome_atributo=False)
    id_palavra_chave = forms.MultipleChoiceField(
        required=True,
        widget=forms.CheckboxSelectMultiple,
        choices=palavra_chave,
        label="Palavras Chaves",
    )

    BD.close()

    def __init__(self, *args, **kwargs):
        self.acao = kwargs.pop('acao', None)
        self.id = kwargs.pop('id', None)
        super(ObraForm, self).__init__(*args, **kwargs)

        if self.acao == "editar":
            usuario = "postgres"
            senha = "admin123"

            tabela = "Obra"

            atributos = []
            atributos.append(['isbn', 'titulo', 'ano_publicacao'])
            atributos.append('id_autor')
            atributos.append('id_genero')
            atributos.append('id_palavra_chave')
            atributos.append('id_editora')

            join_ = []
            join_.append('')
            join_.append("JOIN Autoria USING(id_obra) " +
                         "JOIN Autor USING(id_autor)")
            join_.append("JOIN Classificacao USING(id_obra) " +
                         "JOIN Genero USING (id_genero)")
            join_.append("JOIN Assunto USING(id_obra)" +
                         "JOIN Palavras_Chaves USING (id_palavra_chave)")
            join_.append("JOIN Editora USING (id_editora)")

            BD = ConexaoBD("localhost", "SistemaBiblioteca", usuario, senha)

            condicao = "id_obra = %s" % self.id

            OBRA = 0
            AUTOR = 1
            GENERO = 2
            PALAVRA_CHAVE = 3
            EDITORA = 4

            self.preenche_campos_texto(BD, tabela, atributos[OBRA], condicao,
                                       join_[OBRA])
            self.preenche_campos_select(BD, tabela, atributos[AUTOR], condicao,
                                        join_[AUTOR])
            self.preenche_campos_checkbox(BD, tabela, atributos[GENERO],
                                          condicao, join_[GENERO])
            self.preenche_campos_checkbox(BD, tabela, atributos[PALAVRA_CHAVE],
                                          condicao, join_[PALAVRA_CHAVE])
            self.preenche_campos_select(BD, tabela, atributos[EDITORA],
                                        condicao, join_[EDITORA])

    def preenche_campos_texto(self,
                              BD,
                              tabela,
                              atributos,
                              condicao,
                              join_=None):
        obra_informacoes = BD.select(tabela,
                                     atributos,
                                     where=condicao,
                                     join=join_)
        obra_informacoes = obra_informacoes[0]

        atributos = valida_lista(atributos)

        for atributo in atributos:
            self.fields[atributo].widget.attrs['value'] = obra_informacoes[
                atributo]

    def preenche_campos_checkbox(self,
                                 BD,
                                 tabela,
                                 atributo,
                                 condicao,
                                 join_=None):
        obra_informacoes = BD.select(tabela,
                                     atributo,
                                     where=condicao,
                                     join=join_)

        lista_checked = []

        for informacoes in obra_informacoes:
            lista_checked.append(informacoes[atributo])

        self.fields[atributo].initial = lista_checked

    def preenche_campos_select(self,
                               BD,
                               tabela,
                               atributo,
                               condicao,
                               join_=None):
        obra_informacoes = BD.select(tabela,
                                     atributo,
                                     where=condicao,
                                     join=join_)
        obra_informacoes = obra_informacoes[0]

        self.fields[atributo].initial = obra_informacoes[atributo]
Example #2
0
class AccountForm(forms.ModelForm):
    teams_queryset = []
    teams = forms.MultipleChoiceField(choices=teams_queryset)

    def __init__(self, *args, **kwargs):
        account_view = kwargs.pop('account', False)
        request_user = kwargs.pop('request_user', None)
        super(AccountForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs = {"class": "form-control"}
        self.fields['description'].widget.attrs.update({'rows': '8'})
        self.fields['status'].choices = [
            (each[0], each[1]) for each in Account.ACCOUNT_STATUS_CHOICE]
        self.fields['status'].required = False
        self.fields['phone'].required = False
        self.fields['email'].required = False
        self.fields['contacts'].required = False
        # for key, value in self.fields.items():
        #     if key == 'phone':
        #         value.widget.attrs['placeholder'] = "Phone Number"
        #     else:
        #         value.widget.attrs['placeholder'] = value.label

        self.fields['billing_address_line'].widget.attrs.update({
            'placeholder': 'Address Line'})
        self.fields['billing_street'].widget.attrs.update({
            'placeholder': 'Street'})
        self.fields['billing_city'].widget.attrs.update({
            'placeholder': 'City'})
        self.fields['billing_state'].widget.attrs.update({
            'placeholder': 'State'})
        self.fields['billing_postcode'].widget.attrs.update({
            'placeholder': 'Postcode'})
        self.fields["billing_country"].choices = [
            ("", "--Country--"), ] + list(self.fields["billing_country"].choices)[1:]
        # self.fields["lead"].queryset = Lead.objects.all(
        # ).exclude(status='closed')
        if request_user.role == 'ADMIN':
            self.fields["lead"].queryset = Lead.objects.filter().exclude(
                status='closed').order_by('title')
            self.fields["contacts"].queryset = Contact.objects.filter()
            self.fields["teams"].choices = [(team.get('id'), team.get('name')) for team in Teams.objects.all().values('id', 'name')]
            self.fields["teams"].required = False
        else:
            self.fields["lead"].queryset = Lead.objects.filter(
                Q(assigned_to__in=[request_user]) | Q(created_by=request_user)).exclude(status='closed').order_by('title')
            self.fields["contacts"].queryset = Contact.objects.filter(
                Q(assigned_to__in=[request_user]) | Q(created_by=request_user))
            self.fields["teams"].required = False

        self.fields['assigned_to'].required = False
        if account_view:
            self.fields['billing_address_line'].required = False
            self.fields['billing_street'].required = False
            self.fields['billing_city'].required = False
            self.fields['billing_state'].required = False
            self.fields['billing_postcode'].required = False
            self.fields['billing_country'].required = False

        # lead is not mandatory while editing
        if self.instance.id:
            self.fields['lead'].required = False
        self.fields['lead'].required = False

    class Meta:
        model = Account
        fields = ('name', 'phone', 'email', 'website', 'industry',
                  'description', 'status', 'assigned_to',
                  'billing_address_line', 'billing_street',
                  'billing_city', 'billing_state',
                  'billing_postcode', 'billing_country', 'lead', 'contacts')

        widgets = {
            'phone': forms.NumberInput(attrs={'class': 'form-control','type': 'number'}),
        }
Example #3
0
class PrefixFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm):
    model = Prefix
    field_order = [
        'q', 'within_include', 'family', 'mask_length', 'vrf_id', 'status', 'site', 'role', 'tenant_group', 'tenant',
        'is_pool', 'expand',
    ]
    q = forms.CharField(
        required=False,
        label='Search'
    )
    within_include = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Prefix',
            }
        ),
        label='Search within'
    )
    family = forms.ChoiceField(
        required=False,
        choices=IP_FAMILY_CHOICES,
        label='Address family',
        widget=StaticSelect2()
    )
    mask_length = forms.ChoiceField(
        required=False,
        choices=PREFIX_MASK_LENGTH_CHOICES,
        label='Mask length',
        widget=StaticSelect2()
    )
    vrf_id = FilterChoiceField(
        queryset=VRF.objects.all(),
        label='VRF',
        null_label='-- Global --',
        widget=APISelectMultiple(
            api_url="/api/ipam/vrfs/",
            null_option=True,
        )
    )
    status = forms.MultipleChoiceField(
        choices=PREFIX_STATUS_CHOICES,
        required=False,
        widget=StaticSelect2Multiple()
    )
    site = FilterChoiceField(
        queryset=Site.objects.all(),
        to_field_name='slug',
        null_label='-- None --',
        widget=APISelectMultiple(
            api_url="/api/dcim/sites/",
            value_field="slug",
            null_option=True,
        )
    )
    role = FilterChoiceField(
        queryset=Role.objects.all(),
        to_field_name='slug',
        null_label='-- None --',
        widget=APISelectMultiple(
            api_url="/api/ipam/roles/",
            value_field="slug",
            null_option=True,
        )
    )
    is_pool = forms.NullBooleanField(
        required=False,
        label='Is a pool',
        widget=StaticSelect2(
            choices=BOOLEAN_WITH_BLANK_CHOICES
        )
    )
    expand = forms.BooleanField(
        required=False,
        label='Expand prefix hierarchy'
    )
Example #4
0
class SearchForm( forms.Form ):

    log.debug( 'SearchForm() class loaded' )

    def __init__(self, *args, **kwargs):
        """ Builds choices dynamically.
            <https://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field> """
        #
        super(SearchForm, self).__init__(*args, **kwargs)
        log.debug( 'SearchForm() instantiated' )
        log.debug( '*args, ```%s```' % args )
        log.debug( '**kwargs, ```%s```' % kwargs )
        #
        # url = 'https://127.0.0.1/test/dev/django_choices.json'
        # r = requests.get( url )
        # log.debug( 'r.content, ```%s```' % r.content )
        # self.choice_places = json.loads( r.content )
        #
        self.choice_places = [(item, item) for item in sorted( common.facetResults('placeMenu').keys()) if item]
        # self.fields['place'] = forms.MultipleChoiceField(required=False, choices=self.choice_places, widget=forms.SelectMultiple(attrs={'size':'10'}))
        self.fields['place'] = forms.MultipleChoiceField(required=False, choices=self.choice_places, widget=forms.CheckboxSelectMultiple())
        #
        self.vocab_request = requests.get("https://cds.library.brown.edu/projects/iip/include_taxonomies.xml")
        self.vocab = ET.fromstring(self.vocab_request.content)
        self.taxonomies = self.vocab.findall('{http://www.tei-c.org/ns/1.0}taxonomy')
        #
        log.debug( 'type(self.taxonomies), `%s`' % type(self.taxonomies) )
        log.debug( 'self.taxonomies[0].attrib.values(), ```%s```' % self.taxonomies[0].attrib.values() )
        log.debug( 'tax.attrib.values(), ```%s```' % [tax.attrib.values() for tax in self.taxonomies] )
        # self.type_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-genre'][0]
        self.type_tax = [tax for tax in self.taxonomies if list( tax.attrib.values() )[0] == 'IIP-genre'][0]
        # self.types_dict = dict([(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.type_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        #self.types_dict = dict([( list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text ) for element in self.type_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.types_dict = dict([(list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text.lstrip('-')) for element in self.type_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.choice_types = make_vocab_list( self.types_dict, sorted( common.facetResults('type').keys()) )
        # self.fields['type'] = forms.MultipleChoiceField(required=False, choices=self.choice_types, widget=forms.SelectMultiple(attrs={'size':'7'}))
        self.fields['type'] = forms.MultipleChoiceField(required=False, choices=self.choice_types, widget=forms.CheckboxSelectMultiple())
        #
        # self.phys_types_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-form'][0]
        self.phys_types_tax = [tax for tax in self.taxonomies if list( tax.attrib.values() )[0] == 'IIP-form'][0]
        # self.physical_types_dict = dict([(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.phys_types_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.physical_types_dict = dict([( list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text ) for element in self.phys_types_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.physical_types = make_vocab_list(self.physical_types_dict, sorted( common.facetResults('physical_type').keys()))
        # self.fields['physical_type'] = forms.MultipleChoiceField(required=False, choices=self.physical_types, widget=forms.SelectMultiple(attrs={'size':'7'}))
        self.fields['physical_type'] = forms.MultipleChoiceField(required=False, choices=self.physical_types, widget=forms.CheckboxSelectMultiple())
        #
        # self.religions_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-religion'][0]
        self.religions_tax = [tax for tax in self.taxonomies if list( tax.attrib.values() )[0] == 'IIP-religion'][0]
        # self.religions = [(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.religions_tax.findall('{http://www.tei-c.org/ns/1.0}category')]
        self.religions = [( list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text ) for element in self.religions_tax.findall('{http://www.tei-c.org/ns/1.0}category')]
        # self.fields['religion'] = forms.MultipleChoiceField(required=False, choices=self.religions, widget=forms.CheckboxSelectMultiple)
        self.fields['religion'] = forms.MultipleChoiceField(required=False, choices=self.religions, widget=forms.CheckboxSelectMultiple(attrs={'class': 'styled'}))
        #
        self.languages_dict = {
            "he":"Hebrew",
            "la": "Latin",
            "grc": "Greek",
            "arc": "Aramaic",
            "x-unknown":"Unknown"
            }
        self.languages = make_vocab_list(self.languages_dict, sorted( common.facetResults('language').keys()))
        # self.fields['language'] = forms.MultipleChoiceField(required=False, choices=self.languages, widget=forms.CheckboxSelectMultiple)
        self.fields['language'] = forms.MultipleChoiceField(required=False, choices=self.languages, widget=forms.CheckboxSelectMultiple())

        # self.material_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-materials'][0]
        self.material_tax = [tax for tax in self.taxonomies if list(tax.attrib.values())[0] == 'IIP-materials'][0]
        # self.materials_dict = dict([(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.material_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.materials_dict = dict([(list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.material_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.materials = make_vocab_list( self.materials_dict, sorted( common.facetResults('material').keys()) )
        self.fields['material'] = forms.MultipleChoiceField(required=False, choices=self.materials, widget=forms.CheckboxSelectMultiple())
    text = forms.CharField(required=False)
    metadata = forms.CharField(required=False)
    figure = forms.CharField(required=False)
    #
    DISPLAY_STATUSES = [
    ('approved', 'Approved'),  # ( 'value', 'label' )
    ('to_approve', 'To Approve'),
    ('to_correct', 'To Correct') ]
    display_status = forms.MultipleChoiceField(required=False, choices=DISPLAY_STATUSES, widget=forms.CheckboxSelectMultiple)
    #
    notBefore = forms.CharField(required=False, max_length=5)
    notAfter = forms.CharField(required=False, max_length=5)
    afterDateEra = forms.ChoiceField(required=False, choices=(('bce','BCE'),('ce','CE')), widget=forms.RadioSelect)
    beforeDateEra = forms.ChoiceField(required=False, choices=(('bce','BCE'),('ce','CE')), widget=forms.RadioSelect)
    # select_multiple = dict.fromkeys(['type', 'physical_type', 'language', 'religion', 'material'], "on")
    type_ = forms.ChoiceField(required=True, choices=(('or', 'OR'), ('and', 'AND')), widget = forms.RadioSelect(attrs={'class': 'select-multiple-toggle'}), label="select")
    physical_type_ = forms.ChoiceField(required=True, choices=(('or', 'OR'), ('and', 'AND')), widget = forms.RadioSelect(attrs={'class': 'select-multiple-toggle'}))
    language_ = forms.ChoiceField(required=True, choices=(('or', 'OR'), ('and', 'AND')), widget = forms.RadioSelect(attrs={'class': 'select-multiple-toggle'}))
    religion_ = forms.ChoiceField(required=True, choices=(('or', 'OR'), ('and', 'AND')), widget = forms.RadioSelect(attrs={'class': 'select-multiple-toggle'}))
    material_ = forms.ChoiceField(required=True, choices=(('or', 'OR'), ('and', 'AND')), widget = forms.RadioSelect(attrs={'class': 'select-multiple-toggle'}))

    # url = 'https://127.0.0.1/test/dev/django_choices.json'
    # r = requests.get( url )
    # log.debug( 'r.content, ```%s```' % r.content )
    # places = json.loads( r.content )
    # place = forms.MultipleChoiceField(required=False, choices=places, widget=forms.SelectMultiple(attrs={'size':'10'}))

    def generateSolrQuery(self):
        log.debug( 'starting generateSolrQuery()' )
        # search_fields = ('text','metadata','figure','region','city','place','type','physical_type','language','religion','notBefore','notAfter', 'display_status')
        search_fields = ('text','metadata','figure','region','city','place','type','physical_type','language','religion','material','notBefore','notAfter', 'display_status')
        response = ''
        first = True
        concat_operators = {
            'type': self.cleaned_data['type_'].upper(),
            'physical_type': self.cleaned_data['physical_type_'].upper(),
            'language': self.cleaned_data['language_'].upper(),
            'religion': self.cleaned_data['religion_'].upper(),
            'material': self.cleaned_data['material_'].upper()
        }
        log.debug( 'concat_operators, ```%s```' % concat_operators )
        log.debug( 'self.cleaned_data.items(), ```%s```' % self.cleaned_data.items() )
        for f,v in self.cleaned_data.items(): # f = facet (place, type, etc.), v = value (["altar, amphora"])
            #The following is specific to the date-encoding in the IIP & US Epigraphy projects
            #If youre using this code for other projects, you probably want to omit them
            if ((f == u'notBefore') or (f == u'notAfter')) and v:
                v = doDateEra(self,f,v)
            # End custom blocks
            elif v:
                if isinstance(v, list): #if multiple values selected for a facet (e.g. v = ["altar, amphora"])
                    vListFirst = True
                    vlist = ''
                    for c in v:
                        if re.search( '\s', str(c) ):
                            c = u"\"%s\"" % c
                        if vListFirst:
                            vListFirst = False
                        else:
                            vlist += (' ' + concat_operators[f] + ' ' + f + ":")
                        vlist += u"%s" % c
                    v = u"%s" % vlist
                else:
                    if re.search('\s', str(v)):
                        v = u"\"%s\"" % v
            if f and v:
                if f in search_fields:
                    log.debug( f'f, ```{f}```; v, ```{v}```' )
                    if first:
                        first = False
                    else:
                        if(v != ''): response += " AND "
                    if(v != ''): response += u"(%s:%s)" % (f,v)
        log.debug( f'response, ```{response}```' )
        return response
Example #5
0
class FilterForm(forms.ModelForm):
    work_type = forms.MultipleChoiceField(
        choices=PortfolioCategory.WORK_TYPE,
        widget=RenderedCheckboxSelectMultiple)
    category = forms.MultipleChoiceField(choices=PortfolioCategory.CATEGORY,
                                         widget=RenderedCheckboxSelectMultiple)
    query = forms.CharField(initial='szukaj w portfolio')
    country = forms.ModelChoiceField(queryset=Region.objects.filter(
        type=Region.REGION_COUNTRY).order_by('name'))
    voyvodship = forms.ModelChoiceField(queryset=Region.objects.filter(
        type=Region.REGION_VOYVODSHIP).order_by('name'))
    city = forms.ModelChoiceField(queryset=Region.objects.filter(
        type=Region.REGION_CITY).order_by('name'))

    class Meta:
        model = Portfolio

    def __init__(self, data=None, *args, **kwargs):
        super(FilterForm, self).__init__(data, *args, **kwargs)
        if data:
            region = Region.get_root_nodes()[0]
            self.fields['country'].queryset = region.get_descendants().filter(
                type=Region.REGION_COUNTRY).order_by('name')
            country = data.get('country', None)
            if country:
                try:
                    region = region.get_descendants().get(pk=country)
                except Region.DoesNotExist:
                    pass
                else:
                    self.fields[
                        'voyvodship'].queryset = region.get_descendants(
                        ).filter(
                            type=Region.REGION_VOYVODSHIP).order_by('name')
                    self.fields['city'].queryset = region.get_descendants(
                    ).filter(type=Region.REGION_CITY).order_by('name')
            voyvodship = data.get('voyvodship', None)
            if voyvodship:
                try:
                    region = region.get_descendants().get(pk=voyvodship)
                except Region.DoesNotExist:
                    pass
                else:
                    self.fields['city'].queryset = region.get_descendants(
                    ).filter(type=Region.REGION_CITY).order_by('name')
            city = data.get('city', None)
            if city:
                try:
                    region = region.get_descendants().get(pk=city)
                except Region.DoesNotExist:
                    pass
            categories = list(
                PortfolioCategory.objects.filter(
                    portfolio__region__in=Region.get_tree(region)).values(
                        'work_type', 'category'))
            work_types = set(
                [int(category['work_type']) for category in categories])
            self.fields['work_type'].choices = [
                (key, value) for key, value in PortfolioCategory.WORK_TYPE
                if key in work_types
            ]
Example #6
0
class OrgExtForm(OrgForm):
    """Also configure available languages for this organization.

    The motivation is that given a many-org (i.e., country) installation,
    the global list of languages could get very long.
    Each org is probably interested in seeing only a subset of those languages.
    """

    available_languages = forms.MultipleChoiceField(
        choices=settings.LANGUAGES,
        help_text=_(
            "The languages used by administrators in your organization"))
    show_spoof_data = forms.BooleanField(
        required=False,
        help_text=_("Whether to show spoof data for this organization."))
    contact_fields = forms.ModelMultipleChoiceField(
        queryset=None,
        required=False,
        help_text=_("Custom contact data fields that should be visible "
                    "and editable in TracPro."))

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

        # Modify the language field to better match our usage.
        language = self.fields['language']
        language.required = True
        language.label = _("Default language")
        language.help_text = _("The default language for your organization")

        # All orgs must use a subdomain.
        self.fields['subdomain'].required = True

        # Config field values are not set automatically.
        self.fields['available_languages'].initial = self.instance.available_languages or []
        self.fields[
            'show_spoof_data'].initial = self.instance.show_spoof_data or False

        if not self.instance.pk:
            # We don't have this org's API key yet,
            # so we can't get available fields from the RapidPro API.
            self.fields.pop('contact_fields')
        else:
            try:
                # Make sure we have the most up-to-date DataField info.
                # NOTE: This makes an in-band request to an external API.
                DataField.objects.sync(self.instance)
            except TembaAPIError as e:
                if utils.caused_by_bad_api_key(e):
                    # Org has an invalid API key, but user needs to be
                    # able to access this form in order to update it.
                    pass
                else:
                    raise

            data_fields = self.instance.datafield_set.all()
            self.fields['contact_fields'].queryset = data_fields
            self.fields['contact_fields'].initial = data_fields.visible()

    def clean(self):
        """Ensure the default language is chosen from the available languages."""
        language = self.cleaned_data.get('language')
        available_languages = self.cleaned_data.get(
            'available_languages') or []
        if language and available_languages:  # otherwise, default errors are preferred
            if language not in available_languages:
                raise forms.ValidationError(
                    _("Default language must be one of the languages available "
                      "for this organization."))
        return self.cleaned_data

    def save(self, *args, **kwargs):
        # Config field values are not set automatically.
        if 'available_languages' in self.fields:
            available_languages = self.cleaned_data.get('available_languages')
            self.instance.available_languages = available_languages or []
        if 'show_spoof_data' in self.fields:
            show_spoof_data = self.cleaned_data.get('show_spoof_data')
            self.instance.show_spoof_data = show_spoof_data or False

        if 'contact_fields' in self.fields:
            # Set hook that will be picked up by a post-save signal.
            # Must be done post-save to avoid making changes if any earlier
            # part of the transaction fails.
            self.instance._visible_data_fields = self.cleaned_data.get(
                'contact_fields')

        return super(OrgExtForm, self).save(*args, **kwargs)
Example #7
0
class RevisionForm(AkismetCheckFormMixin, forms.ModelForm):
    """
    Form to create new revisions.
    """
    title = StrippedCharField(
        min_length=1,
        max_length=255,
        required=False,
        widget=forms.TextInput(attrs={'placeholder': TITLE_PLACEHOLDER}),
        label=_(u'Title:'),
        help_text=_(u'Title of article'),
        error_messages={
            'required': TITLE_REQUIRED,
            'min_length': TITLE_SHORT,
            'max_length': TITLE_LONG,
        })

    slug = StrippedCharField(min_length=1,
                             max_length=255,
                             required=False,
                             widget=forms.TextInput(),
                             label=_(u'Slug:'),
                             help_text=_(u'Article URL'),
                             error_messages={
                                 'required': SLUG_REQUIRED,
                                 'min_length': SLUG_SHORT,
                                 'max_length': SLUG_LONG,
                             })

    tags = StrippedCharField(
        required=False,
        label=_(u'Tags:'),
    )

    keywords = StrippedCharField(
        required=False,
        label=_(u'Keywords:'),
        help_text=_(u'Affects search results'),
    )

    summary = StrippedCharField(
        required=False,
        min_length=5,
        max_length=1000,
        widget=forms.Textarea(),
        label=_(u'Search result summary:'),
        help_text=_(u'Only displayed on search results page'),
        error_messages={
            'required': SUMMARY_REQUIRED,
            'min_length': SUMMARY_SHORT,
            'max_length': SUMMARY_LONG
        },
    )

    content = StrippedCharField(min_length=5,
                                max_length=300000,
                                label=_(u'Content:'),
                                widget=forms.Textarea(),
                                error_messages={
                                    'required': CONTENT_REQUIRED,
                                    'min_length': CONTENT_SHORT,
                                    'max_length': CONTENT_LONG,
                                })

    comment = StrippedCharField(required=False, label=_(u'Comment:'))

    review_tags = forms.MultipleChoiceField(
        label=ugettext("Tag this revision for review?"),
        widget=CheckboxSelectMultiple,
        required=False,
        choices=REVIEW_FLAG_TAGS,
    )

    localization_tags = forms.MultipleChoiceField(
        label=ugettext("Tag this revision for localization?"),
        widget=CheckboxSelectMultiple,
        required=False,
        choices=LOCALIZATION_FLAG_TAGS,
    )

    current_rev = forms.CharField(
        required=False,
        widget=forms.HiddenInput(),
    )

    class Meta(object):
        model = Revision
        fields = ('title', 'slug', 'tags', 'keywords', 'summary', 'content',
                  'comment', 'based_on', 'toc_depth', 'render_max_age')

    def __init__(self, *args, **kwargs):
        self.section_id = kwargs.pop('section_id', None)
        self.is_iframe_target = kwargs.pop('is_iframe_target', None)

        # when creating a new document with a parent, this will be set
        self.parent_slug = kwargs.pop('parent_slug', None)

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

        self.fields['based_on'].widget = forms.HiddenInput()

        if self.instance and self.instance.pk:
            # Ensure both title and slug are populated from parent document,
            # if last revision didn't have them
            if not self.instance.title:
                self.initial['title'] = self.instance.document.title
            if not self.instance.slug:
                self.initial['slug'] = self.instance.document.slug

            content = self.instance.content
            if not self.instance.document.is_template:
                parsed_content = kuma.wiki.content.parse(content)
                parsed_content.injectSectionIDs()
                if self.section_id:
                    parsed_content.extractSection(self.section_id)
                parsed_content.filterEditorSafety()
                content = parsed_content.serialize()
            self.initial['content'] = content

            self.initial['review_tags'] = list(
                self.instance.review_tags.names())
            self.initial['localization_tags'] = list(
                self.instance.localization_tags.names())

        if self.section_id:
            self.fields['toc_depth'].required = False

    def clean_slug(self):
        # Since this form can change the URL of the page on which the editing
        # happens, changes to the slug are ignored for an iframe submissions
        if self.is_iframe_target:
            return self.instance.document.slug

        # Get the cleaned slug
        slug = self.cleaned_data['slug']

        # first check if the given slug doesn't contain slashes and other
        # characters not allowed in a revision slug component (without parent)
        if slug and INVALID_REV_SLUG_CHARS_RE.search(slug):
            raise forms.ValidationError(SLUG_INVALID)

        # edits can come in without a slug, so default to the current doc slug
        if not slug:
            try:
                slug = self.instance.slug = self.instance.document.slug
            except ObjectDoesNotExist:
                pass

        # then if there is a parent document we prefix the slug with its slug
        if self.parent_slug:
            slug = u'/'.join([self.parent_slug, slug])

        try:
            doc = Document.objects.get(locale=self.instance.document.locale,
                                       slug=slug)
            if self.instance and self.instance.document:
                if (not doc.get_redirect_url()
                        and doc.pk != self.instance.document.pk):
                    # There's another document with this value,
                    # and we're not a revision of it.
                    raise forms.ValidationError(SLUG_COLLIDES)
            else:
                # This document-and-revision doesn't exist yet, so there
                # shouldn't be any collisions at all.
                raise forms.ValidationError(SLUG_COLLIDES)

        except Document.DoesNotExist:
            # No existing document for this value, so we're good here.
            pass

        return slug

    def clean_tags(self):
        """
        Validate the tags ensuring we have no case-sensitive duplicates.
        """
        tags = self.cleaned_data['tags']
        cleaned_tags = []

        if tags:
            for tag in parse_tags(tags):
                # Note: The exact match query doesn't work correctly with
                # MySQL with regards to case-sensitivity. If we move to
                # Postgresql in the future this code may need to change.
                doc_tag = (DocumentTag.objects.filter(
                    name__exact=tag).values_list('name', flat=True))

                # Write a log we can grep to help find pre-existing duplicate
                # document tags for cleanup.
                if len(doc_tag) > 1:
                    log.warn('Found duplicate document tags: %s' % doc_tag)

                if doc_tag:
                    if doc_tag[0] != tag and doc_tag[0].lower() == tag.lower():
                        # The tag differs only by case. Do not add a new one,
                        # add the existing one.
                        cleaned_tags.append(doc_tag[0])
                        continue

                cleaned_tags.append(tag)

        return ' '.join([u'"%s"' % t for t in cleaned_tags])

    def clean_content(self):
        """
        Validate the content, performing any section editing if necessary
        """
        content = self.cleaned_data['content']

        # If we're editing a section, we need to replace the section content
        # from the current revision.
        if self.section_id and self.instance and self.instance.document:
            # Make sure we start with content form the latest revision.
            full_content = self.instance.document.current_revision.content
            # Replace the section content with the form content.
            parsed_content = kuma.wiki.content.parse(full_content)
            parsed_content.replaceSection(self.section_id, content)
            content = parsed_content.serialize()

        return content

    def clean_current_rev(self):
        """
        If a current revision is supplied in the form, compare it against
        what the document claims is the current revision. If there's a
        difference, then an edit has occurred since the form was constructed
        and we treat it as a mid-air collision.
        """
        current_rev = self.cleaned_data.get('current_rev', None)

        if not current_rev:
            # If there's no current_rev, just bail.
            return current_rev

        try:
            doc_current_rev = self.instance.document.current_revision.id
            if unicode(current_rev) != unicode(doc_current_rev):

                if (self.section_id and self.instance
                        and self.instance.document):
                    # This is a section edit. So, even though the revision has
                    # changed, it still might not be a collision if the section
                    # in particular hasn't changed.
                    orig_ct = (Revision.objects.get(
                        pk=current_rev).get_section_content(self.section_id))
                    curr_ct = (self.instance.document.current_revision.
                               get_section_content(self.section_id))
                    if orig_ct != curr_ct:
                        # Oops. Looks like the section did actually get
                        # changed, so yeah this is a collision.
                        raise forms.ValidationError(MIDAIR_COLLISION)

                    return current_rev

                else:
                    # No section edit, so this is a flat-out collision.
                    raise forms.ValidationError(MIDAIR_COLLISION)

        except Document.DoesNotExist:
            # If there's no document yet, just bail.
            return current_rev

    def akismet_enabled(self):
        """
        Makes sure that users that have been granted the
        'wiki_akismet_exempted' waffle flag are exempted from spam checks.
        """
        client_ready = super(RevisionForm, self).akismet_enabled()
        user_exempted = waffle.flag_is_active(self.request, SPAM_EXEMPTED_FLAG)
        return client_ready and not user_exempted

    @property
    def akismet_error_message(self):
        return mark_safe(render_to_string('wiki/includes/spam_error.html', {}))

    def akismet_error(self, parameters, exception=None):
        """
        Upon errors from the Akismet API records the user, document
        and date of the attempt for further analysis. Then call the
        parent class' error handler.
        """
        try:
            document = self.instance.document
        except ObjectDoesNotExist:
            document = None

        if exception and isinstance(exception, AkismetError):
            # For Akismet errors, save the submission and exception details
            dsa_params = parameters.copy()
            dsa_params['akismet_status_code'] = exception.status_code
            dsa_params['akismet_debug_help'] = exception.debug_help
            dsa_params['akismet_response'] = exception.response.content
            review = DocumentSpamAttempt.AKISMET_ERROR
        else:
            # For detected spam, save the details for review
            dsa_params = parameters
            review = DocumentSpamAttempt.NEEDS_REVIEW

        # Wrapping this in a try/finally to make sure that even if
        # creating a spam attempt object fails we call the parent
        # method that raises a ValidationError
        try:
            DocumentSpamAttempt.objects.create(
                title=self.cleaned_data['title'],
                slug=self.cleaned_data['slug'],
                user=self.request.user,
                document=document,
                data=json.dumps(dsa_params),
                review=review)
        finally:
            if not waffle.flag_is_active(self.request, SPAM_TRAINING_FLAG):
                super(RevisionForm, self).akismet_error(parameters, exception)

    def akismet_parameters(self):
        """
        Returns a dict of parameters to pass to Akismet's submission
        API endpoints. Uses the given form and form parameters to
        build the dict.

        Must follow the data used for retrieving a dict of this data
        for a model instance in
        ``RevisionAkismetSubmissionAdminForm.akismet_parameters`` method!
        """
        default_language = settings.WIKI_DEFAULT_LANGUAGE

        # Try to get the language depending on source -- either the instance
        # provided or the POST data. Fall back to the default defined in
        # settings.
        if self.instance and self.instance.pk and self.instance.document:
            language = self.instance.document.locale or default_language
        else:
            language = self.data.get('locale', default_language)

        # If language is not the default, include the default in case of
        # partial translations. Also convert locale from 'en-US' to 'en_us'.
        if language == default_language:
            blog_lang = self.akismet_locale(language)
        else:
            blog_lang = '%s, %s' % (self.akismet_locale(language),
                                    self.akismet_locale(default_language))

        content = u'\n'.join([
            self.cleaned_data.get(field, '')
            for field in SPAM_SUBMISSION_REVISION_FIELDS
        ])

        parameters = {
            'blog_lang': blog_lang,
            'blog_charset': 'UTF-8',
            'comment_author': author_from_user(self.request.user),
            'comment_author_email': author_email_from_user(self.request.user),
            'comment_content': content,
            'comment_type': 'wiki-revision',
            'user_ip': self.request.META.get('REMOTE_ADDR', ''),
            'user_agent': self.request.META.get('HTTP_USER_AGENT', ''),
            'referrer': self.request.META.get('HTTP_REFERER', ''),
        }
        parameters.update(self.akismet_parameter_overrides())
        return parameters

    def save(self, document, **kwargs):
        """
        Persists the revision and returns it.
        Takes the view request and document of the revision.
        Does some specific things when the revision is fully saved.
        """
        # have to check for first edit before we save
        is_first_edit = self.request.user.wiki_revisions().count() == 0

        # Making sure we don't commit the saving right away since we
        # want to do other things here.
        kwargs['commit'] = False

        if self.section_id and self.instance and self.instance.document:
            # The logic to save a section is slightly different and may
            # need to evolve over time; a section edit doesn't submit
            # all the fields, and we need to account for that when we
            # construct the new Revision.
            doc = Document.objects.get(pk=self.instance.document.id)
            old_rev = doc.current_revision
            new_rev = super(RevisionForm, self).save(**kwargs)
            new_rev.document = document
            new_rev.creator = self.request.user
            new_rev.toc_depth = old_rev.toc_depth
            new_rev.save()
            new_rev.review_tags.set(*list(old_rev.review_tags.names()))

        else:
            new_rev = super(RevisionForm, self).save(**kwargs)
            new_rev.document = document
            new_rev.creator = self.request.user
            new_rev.toc_depth = self.cleaned_data['toc_depth']
            new_rev.save()
            new_rev.review_tags.set(*self.cleaned_data['review_tags'])
            new_rev.localization_tags.set(
                *self.cleaned_data['localization_tags'])

            # when enabled store the user's IP address
            if waffle.switch_is_active('store_revision_ips'):
                RevisionIP.objects.log(
                    revision=new_rev,
                    headers=self.request.META,
                )

            # send first edit emails
            if is_first_edit:
                send_first_edit_email.delay(new_rev.pk)

            # schedule a document rendering
            document.schedule_rendering('max-age=0')

            # schedule event notifications
            EditDocumentEvent(new_rev).fire(exclude=new_rev.creator)

        return new_rev
Example #8
0
class LangForm(forms.ModelForm):
    LANG = (('0', 'C'), ('1', 'C++'), ('2', 'Java'), ('3', 'Python'))

    lang = forms.MultipleChoiceField(widget=forms.SelectMultiple,
                                     choices=LANG,
                                     initial="1")
Example #9
0
class SearchForm(FacetedSearchForm):
    search_topics = forms.BooleanField(
        label=_('Search only in topic subjects'), required=False)

    search_poster_name = forms.CharField(
        label=_('Search for poster'),
        help_text=_(
            'Enter a user name to limit the search to a specific user.'),
        max_length=255,
        required=False)

    search_forums = forms.MultipleChoiceField(
        label=_('Search in specific forums'),
        help_text=_('Select the forums you wish to search in.'),
        required=False)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)

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

        # Update some fields
        self.fields['q'].label = _('Search for keywords')
        self.fields['q'].widget.attrs['placeholder'] = _('Keywords or phrase')
        self.fields['search_poster_name'].widget.attrs['placeholder'] = _(
            'Poster name')

        self.allowed_forums = PermissionHandler().get_readable_forums(
            Forum.objects.all(), user)
        if self.allowed_forums:
            self.fields['search_forums'].choices = [
                (f.id, '{} {}'.format('-' * f.margin_level, f.name))
                for f in self.allowed_forums
            ]
        else:
            # The user cannot view any single forum, the 'search_forums' field can be deleted
            del self.fields['search_forums']

    def search(self):
        sqs = super().search()

        if not self.is_valid():
            return self.no_query_found()

        # Handles topic-based searches
        if self.cleaned_data['search_topics']:
            sqs = sqs.filter(topic_subject=AutoQuery(self.cleaned_data['q']))

        # Handles searches by poster name
        if self.cleaned_data['search_poster_name']:
            sqs = sqs.filter(
                poster_name__icontains=self.cleaned_data['search_poster_name'])

        # Handles searches in specific forums if necessary
        if 'search_forums' in self.cleaned_data and self.cleaned_data[
                'search_forums']:
            sqs = sqs.filter(forum__in=self.cleaned_data['search_forums'])
        else:
            forum_ids = self.allowed_forums.values_list('id', flat=True)
            sqs = sqs.filter(forum__in=forum_ids) if forum_ids else sqs.none()

        return sqs
Example #10
0
class Add_Alternative(forms.Form):
    CHOICES = (('alt', 'Add Alternative'), )
    add = forms.MultipleChoiceField(choices=CHOICES,
                                    widget=forms.CheckboxSelectMultiple())
Example #11
0
class WeeksSelection_form(forms.Form):
    weeks = forms.MultipleChoiceField(
        choices=timetable_model.WEEKS,
        widget=forms.CheckboxSelectMultiple,
    )
    def rellenarDetalle(self, actividad, contrato):
        #try:
        self.fields['numeroDeSolicitud'].initial = actividad.numeroDeSolicitud
        self.fields['codigoDeCliente'].initial = actividad.cliente.cuenta
        self.fields['nombreDeCliente'].initial = actividad.cliente.nombre
        self.fields['cedula'].initial = actividad.cliente.ci_ruc
        self.fields['estadoCli'].initial = actividad.cliente.estado
        self.fields['telefono'].initial = actividad.cliente.telefono

        if actividad.tipoDeSolicitud_id != 1:
            self.fields['lugar'].initial = actividad.cliente.ubicacionGeografica.parroquia
            self.fields['calle'].initial = actividad.cliente.ubicacionGeografica.calle.descripcion1
            self.fields['geocodigo'].initial = actividad.cliente.geocodigo
        else:
            ref = list(detalleClienteReferencia.objects.filter(
                cliente=actividad.cliente
            ))[0]
            m = list(detalleClienteMedidor.objects.filter(
                cliente=ref.referencia,
                #medidor=ref.medidorDeReferencia
            ))[0].medidor
            self.fields['direccionRef'].initial = ref.referencia.ubicacionGeografica.calle.descripcion1
            self.fields['anterior'].initial = ref.medidorDeReferencia
            self.fields['serieAnteriror'].initial = m.serie
            self.fields['marcaAnteriror'].initial = m.marca
            self.fields['cuentaAnteriror'].initial = ref.referencia.cuenta

        miMed = list(medidor.objects.filter(actividad=actividad, contrato=None))
        if miMed:
            self.fields['fabricaRev'].initial = miMed[0].fabrica
            self.fields['serieRev'].initial = miMed[0].serie
            self.fields['marcaRev'].initial = miMed[0].marca
            self.fields['lecturaRev'].initial = miMed[0].lectura
        miMed = list(medidor.objects.filter(actividad=actividad, contrato__contrato=contrato))
        if miMed:
            self.fields['medidor'].initial = miMed[0]
            self.fields['fabricaInst'].initial = miMed[0].fabrica
            self.fields['serieInst'].initial = miMed[0].serie
            self.fields['marcaInst'].initial = miMed[0].marca
            self.fields['tipoDeMedidor'].initial = miMed[0].tipo
            self.fields['lecturaInst'].initial = miMed[0].lectura

        self.fields['tipoDeSolicitud'].initial = actividad.tipoDeSolicitud
        self.fields['motivoParaSolicitud'].initial = actividad.motivoDeSolicitud
        self.fields['fecha'].initial = actividad.fechaDeActividad
        self.fields['hora'].initial = actividad.horaDeActividad
        self.fields['instalador'].initial = actividad.instalador.nombre
        self.fields['cuadrilla'].initial = actividad.instalador.cuadrilla
        self.fields['materialDeLaRed'].initial = actividad.materialDeLaRed
        self.fields['formaDeConexion'].initial = actividad.formaDeConexion
        self.fields['estadoDeUnaInstalacion'].initial = actividad.estadoDeLaInstalacion
        self.fields['tipoDeConstruccion'].initial = actividad.tipoDeConstruccion
        self.fields['ubicacionDelMedidor'].initial = actividad.ubicacionDelMedidor
        self.fields['tipoDeAcometidaRed'].initial = actividad.tipoDeAcometidaRed
        self.fields['calibreDeLaRed'].initial = actividad.calibreDeLaRed
        self.fields['usoDeEnergia'].initial = actividad.usoDeEnergia
        self.fields['claseRed'].initial = actividad.claseRed
        self.fields['tipoDeServicio'].initial = actividad.tipoDeServicio
        self.fields['usoEspecificoDelInmueble'].initial = actividad.usoEspecificoDelInmueble
        self.fields['demanda'].initial = actividad.demanda
        self.fields['nivelSocieconomico'].initial = actividad.nivelSocieconomico
        self.fields['observaciones'].initial = actividad.observaciones
        try:
            if len(list(detalleDeActividad.objects.filter(
                    actividad=actividad,
                    rubro=detalleRubro.objects.get(
                            contrato=contrato,
                            servicio__id=3,
                            rubro__id=1
                    )))) > 0:
                self.fields['reubicacion'].initial = True
        except:
            pass
        try:
            if len(list(detalleDeActividad.objects.filter(
                    actividad=actividad,
                    rubro=detalleRubro.objects.get(
                            contrato=contrato,
                            servicio__id=4,
                            rubro__id=4
                    )))) > 0:
                self.fields['contrastacion'].initial = True
        except:
            pass
        try:
            if len(list(detalleDeActividad.objects.filter(
                    actividad=actividad,
                    rubro=detalleRubro.objects.get(
                            contrato=contrato,
                            servicio__id=6,
                            rubro__id=2
                    )))) > 0:
                self.fields['directo'].initial = True
        except:
            pass

        #sellos de actividad...
        s = list(sello.objects.filter(utilizado__id=actividad.id))
        ubi = ((i.ubicacion, i.ubicacion) for i in s)
        se = ((i.id, i) for i in s)

        self.fields['sellosSeleccionados'] = forms.MultipleChoiceField(
            choices=se,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )
        self.fields['ubiSellosSeleccionados'] = forms.MultipleChoiceField(
            choices=ubi,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )

        #materiales de actividad...
        s = list(materialDeActividad.objects.filter(actividad__id=actividad.id))
        cant = ((i.cantidad, i.cantidad) for i in s)
        mate = ((i.material.id, i.material) for i in s)

        self.fields['materialesSeleccionados'] = forms.MultipleChoiceField(
            choices=mate,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )
        self.fields['cantMaterialesSeleccionados'] = forms.MultipleChoiceField(
            choices=cant,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )

        self.fields['estadoSolicitud'] = forms.ModelChoiceField(
            estadoDeSolicitud.objects,
            initial=actividad.estadoDeSolicitud.id,
            label=estadoDeSolicitud.objects.get(id=actividad.estadoDeSolicitud.id).descripcion,
            widget=forms.TextInput(
                attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}
            ),
            required=False
        )

        self.fields['id'].initial = actividad.id
class ingresoForm(forms.Form):
    def __init__(self, actividad=None, contrato=None, *args, **kwargs):
        super(ingresoForm, self).__init__(*args, **kwargs)

        if contrato is not None:
            self.fields['material'] = forms.ModelMultipleChoiceField(
                detalleMaterialContrato.objects
                .filter(contrato=contrato)
                .exclude(material__tipoDeMaterial__material__descripcion='KIT '),
                label='Materiales',
                widget=forms.Select(),
                required=False
            )
            # medidores segun contrato...
            self.fields['medidor'] = forms.ModelMultipleChoiceField(
                medidor.objects.filter(
                    contrato__contrato=contrato,
                    est=True,
                    actividad=None
                ), label='En bodega',
                widget=forms.Select(),
                required=False

            )
            # sellos segun contrato...
            self.fields['selloInst'] = forms.ModelMultipleChoiceField(
                sello.objects.filter(detalleMaterialContrato__contrato=contrato, utilizado=None), label='En bodega',
                widget=forms.Select(),
                required=False
            )
        if actividad is not None and contrato is not None:
            self.rellenarDetalle(actividad, contrato)


    #actividad
    id = forms.CharField(
        required=False, initial=0, label='',
        widget=forms.TextInput(attrs={'style': 'height: 0px; padding: 0; margin: 0; border: 0;'}),
    )
    estadoSolicitud = forms.ModelChoiceField(
        estadoDeSolicitud.objects,
        initial=0, label=estadoDeSolicitud.objects.get(id=0).descripcion,
        widget=forms.TextInput(
            attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}
        ),
        required=False
    )
    numeroDeSolicitud = forms.CharField(
        max_length=8, required=False, label='Número do Solicitud',
        widget=forms.TextInput(attrs={
            'style': 'text-align: center; font-size: 1.35em;',
            'readonly': True,
            'placeholder': 'No. de Solicitud'
        }),
        initial='0'
    )
    tipoDeSolicitud = forms.ModelChoiceField(
        tipoDeSolicitud.objects,
        label='Tipo de Solicitud',
        initial=11
    )
    fecha = forms.DateField(
        initial=datetime.date.today(), label='Fecha',
        widget=SelectDateWidget(), required=True
    )
    hora = forms.TimeField(
        initial=timezone.localtime(timezone.now()), label='Hora',
        widget=forms.TimeInput(), required=True
    )

    #Cliente
    codigoDeCliente = forms.CharField(
        max_length=7, min_length=3, label='Código',
        widget=forms.TextInput(attrs={'placeholder': 'Buscar por Cta.'}),
        required=False
    )
    nombreDeCliente = forms.CharField(
        max_length=50, min_length=6, label='Nombre',
        widget=forms.TextInput(attrs={'placeholder': 'Buscar por Nombre'}),
        required=True
    )
    cedula = forms.CharField(
        max_length=13, min_length=10, label='Cédula',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    estadoCli = forms.CharField(
        max_length=30, min_length=1, label='Estado',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    telefono = forms.CharField(
        max_length=11, min_length=7, label='Teléfono',
        widget=forms.TextInput(attrs={'placeholder': 'Teléfono de referencia'}),
        required=False
    )
    lugar = forms.CharField(
        max_length=50, label='Lugar',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    calle = forms.CharField(
        max_length=50, label='Calle',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    geocodigo = forms.CharField(
        max_length=20, label='Geocódigo',
        widget=forms.TextInput(attrs={'placeholder': 'Buscar por Geocodigo'}),
        required=False
    )


    #Medidor(Revisado)
    fabricaRev = forms.CharField(
        max_length=11, label='Fabrica',
        widget=forms.TextInput(attrs={'placeholder': 'Buscar por Merdidor'}),
        required=False
    )
    serieRev = forms.CharField(
        max_length=12, label='Serial',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    marcaRev = forms.CharField(
        max_length=25, label='Marca',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    lecturaRev = forms.CharField(
        max_length=11, label='Lectura',
        widget=forms.TextInput(attrs={'placeholder': 'Digite la lectura del medidor'}),
        required=False
    )


    #Medidor(Instalado)
    medidor = forms.ModelChoiceField(
        medidor.objects, label='En Bodega',
        required=False
    )
    fabricaInst = forms.CharField(
        max_length=11, label='Fabrica',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    serieInst = forms.CharField(
        max_length=10, label='Serial',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    marcaInst = forms.CharField(
        max_length=25, label='Marca',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    tipoDeMedidor = forms.CharField(
        max_length=25, label='Tipo',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    lecturaInst = forms.CharField(
        max_length=6, label='Lectura',
        widget=forms.TextInput(attrs={'placeholder': 'Digite la lectura del medidor'}),
        initial='0',
        required=False
    )


    #Materiales
    material = forms.ModelChoiceField(
        detalleMaterialContrato.objects, label='Materiales',
        widget=forms.Select(),
        required=False
    )
    cantidad = forms.IntegerField(
        max_value=99, min_value=1, label='Cantidad',
        initial=1,
        required=False
    )


    #Detalles de Instalación
    usoEspecificoDelInmueble = forms.ModelChoiceField(
        usoEspecificoDelInmueble.objects,
        label='Uso del Inmueble',
        initial=1, #usoEspecificoDelInmueble.objects.filter(descripcion=' ')[0].id,
        required=True
    )
    usoDeEnergia = forms.ModelChoiceField(
        usoDeEnergia.objects,
        label='Uso de Energía',
        initial='RD',
        required=True
    )
    materialDeLaRed = forms.ModelChoiceField(
        materialDeLaRed.objects,
        label='Material de la Red',
        initial='AL',
        required=True
    )
    tipoDeConstruccion = forms.ModelChoiceField(
        tipoDeConstruccion.objects,
        label='Tipo de Construcción',
        initial=4,
        required=True
    )
    ubicacionDelMedidor = forms.ModelChoiceField(
        ubicacionDelMedidor.objects,
        label='Ubicación del Medidor',
        initial=1,
        required=True
    )
    tipoDeAcometidaRed = forms.ModelChoiceField(
        tipoDeAcometidaRed.objects,
        label='Tipo de Acometida',
        initial='AE',
        required=True
    )
    calibreDeLaRed = forms.ModelChoiceField(
        calibreDeLaRed.objects,
        label='Calibre de Red',
        initial=17,
        required=True
    )
    claseRed = forms.ModelChoiceField(
        claseRed.objects,
        label='Clase de Red',
        initial='D',
        required=True
    )
    nivelSocieconomico = forms.ModelChoiceField(
        nivelSocieconomico.objects,
        label='Nivel Socioeconómico',
        initial='BA',
        required=False
    )
    estadoDeUnaInstalacion = forms.ModelChoiceField(
        estadoDeUnaInstalacion.objects,
        label='Estado de Instalación',
        initial=1
    )
    formaDeConexion = forms.ModelChoiceField(
        formaDeConexion.objects,
        label='Forma de Conexión',
        required=True
        #initial=4
    )
    demanda = forms.ModelChoiceField(
        demanda.objects,
        label='Demanda',
        initial=1
    )
    motivoParaSolicitud = forms.ModelChoiceField(
        motivoParaSolicitud.objects,
        label='Motivo de Solicitud',
        initial=2
    )
    tipoDeServicio = forms.ModelChoiceField(
        tipoDeServicio.objects,
        label='Tipo de Servicio',
        #initial='13B'
        required=True
    )


    #Sello
    selloInst = forms.ModelChoiceField(
        sello.objects, label='En Bodega',
        widget=forms.Select(),
        required=False
    )
    ubicacionDeSello = forms.ChoiceField(
        choices=sello.UBICACIONES,
        label='Ubicacion',
        initial='Caja',
        required=False
    )


    #Referencia
    anterior = forms.CharField(
        max_length=11, label='Fábrica',
        widget=forms.TextInput(attrs={'placeholder': 'Nro. de Medidor de Ref.'}),
        required=False
    )
    serieAnteriror = forms.CharField(
        max_length=15, label='Serie',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    marcaAnteriror = forms.CharField(
        max_length=25, label='Marca',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    cuentaAnteriror = forms.CharField(
        max_length=11, label='Cuenta',
        widget=forms.TextInput(attrs={'readonly': True, 'placeholder': ''}),
        required=False
    )
    direccionRef = forms.CharField(
        max_length=50, label='Dirección',
        widget=forms.TextInput(attrs={'placeholder': 'Digite una dirección de referencia'}),
        required=False
    )


    #Instalador
    instalador = forms.ModelChoiceField(
        empleado.objects,
        label='Instalador',
        required=True
    )
    cuadrilla = forms.ModelChoiceField(
        cuadrilla.objects,
        label='Cuadrilla',
        required=True
    )


    #Observaciones
    observaciones = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.Textarea(
            attrs={
                'placeholder': 'Observaciones de la actividad realizada',
                'rows': "2",
                'cols': "50"
            }
        )
    )

    #Adicionales
    contrastacion = forms.BooleanField(initial=False, label=u'Contrastación', required=False)
    reubicacion = forms.BooleanField(initial=False, label=u'Reubicación', required=False)
    directo = forms.BooleanField(initial=False, label=u'Directo', required=False)

    materialesSeleccionados = forms.MultipleChoiceField(
        widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
        label='',
        required=True,
    )
    cantMaterialesSeleccionados = forms.MultipleChoiceField(
        widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
        required=True
    )
    sellosSeleccionados = forms.MultipleChoiceField(
        widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
        required=True
    )
    ubiSellosSeleccionados = forms.MultipleChoiceField(
        widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
        label='',
        required=True
    )


    def save(self, contrato, cliente=None):
        print self.data['id']

        act = actividad()
        if cliente is not None:
            act.cliente = cliente

        act.tipoDeConstruccion = tipoDeConstruccion.objects.get(id=int(self.data['tipoDeConstruccion']))
        try:
            inst = instalador.objects.get(
                nombre=empleado.objects.get(id=int(self.data['instalador'])),
                cuadrilla=cuadrilla.objects.get(id=int(self.data['cuadrilla']))
            )
        except:
            inst = instalador(
                nombre=empleado.objects.get(id=int(self.data['instalador'])),
                cuadrilla=cuadrilla.objects.get(id=int(self.data['cuadrilla']))
            )
            inst.save()
        act.instalador = inst
        act.ubicacionDelMedidor = ubicacionDelMedidor.objects.get(id=int(self.data['ubicacionDelMedidor']))
        act.claseRed = claseRed.objects.get(id=self.data['claseRed'])
        act.nivelSocieconomico = nivelSocieconomico.objects.get(id=self.data['nivelSocieconomico'])
        act.calibreDeLaRed = calibreDeLaRed.objects.get(id=int(self.data['calibreDeLaRed']))
        act.estadoDeLaInstalacion = estadoDeUnaInstalacion.objects.get(id=int(self.data['estadoDeUnaInstalacion']))
        act.tipoDeAcometidaRed = tipoDeAcometidaRed.objects.get(id=self.data['tipoDeAcometidaRed'])
        act.tipoDeServicio = tipoDeServicio.objects.get(id=self.data['tipoDeServicio'])
        act.fechaDeActividad = datetime.date(
            int(self.data['fecha_year']),
            int(self.data['fecha_month']),
            int(self.data['fecha_day'])
        )
        try:
            act.horaDeActividad = datetime.datetime.strptime(self.data['hora'], '%H:%M:%S')
        except:
            act.horaDeActividad = datetime.time(hour=10, minute=30, second=0)

        act.usoDeEnergia = usoDeEnergia.objects.get(id=self.data['usoDeEnergia'])
        act.usoEspecificoDelInmueble = usoEspecificoDelInmueble.objects.get(id=self.data['usoEspecificoDelInmueble'])
        act.formaDeConexion = formaDeConexion.objects.get(id=int(self.data['formaDeConexion']))
        act.demanda = demanda.objects.get(id=int(self.data['demanda']))
        act.motivoDeSolicitud = motivoParaSolicitud.objects.get(id=int(self.data['motivoParaSolicitud']))
        act.tipoDeSolicitud = tipoDeSolicitud.objects.get(id=int(self.data['tipoDeSolicitud']))
        act.materialDeLaRed = materialDeLaRed.objects.get(id=self.data['materialDeLaRed'])
        act.observaciones = self.data['observaciones']

        if self.data['id'] != '0':
            act.id = self.data['id']
            act.numeroDeSolicitud = self.data['numeroDeSolicitud']
            act.estadoDeSolicitud = estadoDeSolicitud.objects.get(id=int(self.data['estadoSolicitud']))
            act.save(force_update=True)
        else:
            act.save()


            #borrando detalles de existir
            #de medidores...
        for m in list(medidor.objects.filter(actividad__id=act.id)):
            try:
                m.est = True
                m.actividad = None
                m.save(force_update=True)
            except:
                pass


            #de sellos
        for s in list(sello.objects.filter(utilizado__id=act.id)):
            try:
                s.utilizado = None
                s.ubicacion = 'N/A'
                s.save(force_update=True)
            except:
                pass


            #de rubros
        for r in list(detalleDeActividad.objects.filter(actividad__id=act.id)):
            try:
                r.delete()
            except:
                pass


            #de materiales
        for m in list(materialDeActividad.objects.filter(actividad=act)):
            #mat = detalleMaterialContrato.objects.get(id=m.material.id)
            #mat.stock += m.cantidad
            #mat.save(force_update=True)
            m.delete()



            #hay que generar detalles...
            #empezando con medidores
        try:
            medDeActividad = medidor.objects.get(
                fabrica=str(self.data['fabricaRev']),
                serie=str(self.data['serieRev'])
            )
            medDeActividad.est=False
            medDeActividad.actividad = act
            medDeActividad.save(force_update=True)
        except:
            pass
        try:
            medDeActividad = medidor.objects.get(
                fabrica=str(self.data['fabricaInst']),
                serie=str(self.data['serieInst'])
            )
            medDeActividad.est=False
            medDeActividad.lectura=str('%05d' % int(self.data['lecturaInst']))
            medDeActividad.actividad = act
            medDeActividad.save(force_update=True)
        except:
            pass


        #luego con sellos
        sellosInstalados = list(self.data.pop('sellosSeleccionados'))
        ubiSellosInstalados = list(self.data.pop('ubiSellosSeleccionados'))
        print sellosInstalados
        for sell in range(len(sellosInstalados)):
            si = sello.objects.get(id=int(sellosInstalados[sell]))
            si.ubicacion = ubiSellosInstalados[sell]
            si.utilizado = act
            si.save(force_update=True)

            #continuando con detalle de materiales para actividad
        materialInstalado = list(self.data.pop('materialesSeleccionados'))
        cantMaterialInstado = list(self.data.pop('cantMaterialesSeleccionados'))
        #print materialInstalado
        for m in range(len(cantMaterialInstado)):
            mat = detalleMaterialContrato.objects.get(id=int(materialInstalado[m]))
            #print int(materialInstalado[m])
            actMat = materialDeActividad(
                material=mat,
                actividad=act,
                cantidad=long(cantMaterialInstado[m])
            )
            #mat.stock -= actMat.cantidad
            actMat.save()
            #mat.save(force_update=True)

        #actividades realizadas para desgloce de valores a facturar
        realizadas = [[5, 6], [5, 8]]
        if act.tipoDeSolicitud_id == 1:
            realizadas.append([1, 1])
            realizadas.append([5, 7])
            print 'servicio nuevo...'
        elif act.tipoDeSolicitud_id == 11 or act.tipoDeSolicitud_id == 13:
            try:
                if self.data['contrastacion']:
                    realizadas.append([4, 4])
                    print 'Contrastacion...'
            except:
                pass
            try:
                if self.data['reubicacion']:
                    realizadas.append([3, 1])
                    print 'Reubicacion...'
            except:
                pass
            try:
                if materialDeActividad.objects.get(
                        actividad=act,
                        material=detalleMaterialContrato.objects.get(
                                contrato=contrato,
                                material__tipoDeMaterial__material__id=6#cable
                        )
                ):
                    try:
                        if realizadas.index([3, 1]) >= 0:
                            realizadas.append([5, 7])
                            print 'Reubicacion y desgloce para cable...'
                    except ValueError:
                        realizadas.append([4, 3])
                        realizadas.append([5, 7])
                        print 'Hay Solo Acometida...'
            except:
                pass

            if act.tipoDeSolicitud_id == 11:
                try:
                    if materialDeActividad.objects.get(
                            actividad=act,
                            material=detalleMaterialContrato.objects.get(
                                    contrato=contrato,
                                    material__tipoDeMaterial__material__id=4#caja
                            )
                    ):
                        realizadas.append([4, 2])
                        print u'Se realizó cambio de caja...'
                except:
                    try:
                        if materialDeActividad.objects.get(
                                actividad=act,
                                material=detalleMaterialContrato.objects.get(
                                        contrato=contrato,
                                        material__tipoDeMaterial__material__id=16#sello
                                )
                        ) and len(cantMaterialInstado) == 1:
                            realizadas.append([4, 5])
                            print u'Se realizó revision que no incluye material...'
                    except:
                        pass
            elif act.tipoDeSolicitud_id == 13:
                try:
                    if self.data['directo']:
                        realizadas.append([6, 2])
                        print 'Directo...'
                except:
                    realizadas.append([2, 2])
                    print 'Cambio de Medidor...'
                try:
                    if realizadas.index([5, 7]) >= 0:
                        print 'desgloce de Gis...'
                except:
                    realizadas.append([5, 7])
                    print 'se agregó desgloce de Gis...'

        for a in realizadas:
            try:
                actDeta = detalleDeActividad(
                    rubro=detalleRubro.objects.get(
                        servicio__id=a[0],
                        rubro__id=a[1],
                        contrato=contrato
                    ),
                    actividad=act
                )
                actDeta.save()
            except:
                print 'nose pudo guardar :' + str(a)

        print 'Guardado completo de Actividad...id : %s ' % act.id
        return act.id


    def rellenarDetalle(self, actividad, contrato):
        #try:
        self.fields['numeroDeSolicitud'].initial = actividad.numeroDeSolicitud
        self.fields['codigoDeCliente'].initial = actividad.cliente.cuenta
        self.fields['nombreDeCliente'].initial = actividad.cliente.nombre
        self.fields['cedula'].initial = actividad.cliente.ci_ruc
        self.fields['estadoCli'].initial = actividad.cliente.estado
        self.fields['telefono'].initial = actividad.cliente.telefono

        if actividad.tipoDeSolicitud_id != 1:
            self.fields['lugar'].initial = actividad.cliente.ubicacionGeografica.parroquia
            self.fields['calle'].initial = actividad.cliente.ubicacionGeografica.calle.descripcion1
            self.fields['geocodigo'].initial = actividad.cliente.geocodigo
        else:
            ref = list(detalleClienteReferencia.objects.filter(
                cliente=actividad.cliente
            ))[0]
            m = list(detalleClienteMedidor.objects.filter(
                cliente=ref.referencia,
                #medidor=ref.medidorDeReferencia
            ))[0].medidor
            self.fields['direccionRef'].initial = ref.referencia.ubicacionGeografica.calle.descripcion1
            self.fields['anterior'].initial = ref.medidorDeReferencia
            self.fields['serieAnteriror'].initial = m.serie
            self.fields['marcaAnteriror'].initial = m.marca
            self.fields['cuentaAnteriror'].initial = ref.referencia.cuenta

        miMed = list(medidor.objects.filter(actividad=actividad, contrato=None))
        if miMed:
            self.fields['fabricaRev'].initial = miMed[0].fabrica
            self.fields['serieRev'].initial = miMed[0].serie
            self.fields['marcaRev'].initial = miMed[0].marca
            self.fields['lecturaRev'].initial = miMed[0].lectura
        miMed = list(medidor.objects.filter(actividad=actividad, contrato__contrato=contrato))
        if miMed:
            self.fields['medidor'].initial = miMed[0]
            self.fields['fabricaInst'].initial = miMed[0].fabrica
            self.fields['serieInst'].initial = miMed[0].serie
            self.fields['marcaInst'].initial = miMed[0].marca
            self.fields['tipoDeMedidor'].initial = miMed[0].tipo
            self.fields['lecturaInst'].initial = miMed[0].lectura

        self.fields['tipoDeSolicitud'].initial = actividad.tipoDeSolicitud
        self.fields['motivoParaSolicitud'].initial = actividad.motivoDeSolicitud
        self.fields['fecha'].initial = actividad.fechaDeActividad
        self.fields['hora'].initial = actividad.horaDeActividad
        self.fields['instalador'].initial = actividad.instalador.nombre
        self.fields['cuadrilla'].initial = actividad.instalador.cuadrilla
        self.fields['materialDeLaRed'].initial = actividad.materialDeLaRed
        self.fields['formaDeConexion'].initial = actividad.formaDeConexion
        self.fields['estadoDeUnaInstalacion'].initial = actividad.estadoDeLaInstalacion
        self.fields['tipoDeConstruccion'].initial = actividad.tipoDeConstruccion
        self.fields['ubicacionDelMedidor'].initial = actividad.ubicacionDelMedidor
        self.fields['tipoDeAcometidaRed'].initial = actividad.tipoDeAcometidaRed
        self.fields['calibreDeLaRed'].initial = actividad.calibreDeLaRed
        self.fields['usoDeEnergia'].initial = actividad.usoDeEnergia
        self.fields['claseRed'].initial = actividad.claseRed
        self.fields['tipoDeServicio'].initial = actividad.tipoDeServicio
        self.fields['usoEspecificoDelInmueble'].initial = actividad.usoEspecificoDelInmueble
        self.fields['demanda'].initial = actividad.demanda
        self.fields['nivelSocieconomico'].initial = actividad.nivelSocieconomico
        self.fields['observaciones'].initial = actividad.observaciones
        try:
            if len(list(detalleDeActividad.objects.filter(
                    actividad=actividad,
                    rubro=detalleRubro.objects.get(
                            contrato=contrato,
                            servicio__id=3,
                            rubro__id=1
                    )))) > 0:
                self.fields['reubicacion'].initial = True
        except:
            pass
        try:
            if len(list(detalleDeActividad.objects.filter(
                    actividad=actividad,
                    rubro=detalleRubro.objects.get(
                            contrato=contrato,
                            servicio__id=4,
                            rubro__id=4
                    )))) > 0:
                self.fields['contrastacion'].initial = True
        except:
            pass
        try:
            if len(list(detalleDeActividad.objects.filter(
                    actividad=actividad,
                    rubro=detalleRubro.objects.get(
                            contrato=contrato,
                            servicio__id=6,
                            rubro__id=2
                    )))) > 0:
                self.fields['directo'].initial = True
        except:
            pass

        #sellos de actividad...
        s = list(sello.objects.filter(utilizado__id=actividad.id))
        ubi = ((i.ubicacion, i.ubicacion) for i in s)
        se = ((i.id, i) for i in s)

        self.fields['sellosSeleccionados'] = forms.MultipleChoiceField(
            choices=se,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )
        self.fields['ubiSellosSeleccionados'] = forms.MultipleChoiceField(
            choices=ubi,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )

        #materiales de actividad...
        s = list(materialDeActividad.objects.filter(actividad__id=actividad.id))
        cant = ((i.cantidad, i.cantidad) for i in s)
        mate = ((i.material.id, i.material) for i in s)

        self.fields['materialesSeleccionados'] = forms.MultipleChoiceField(
            choices=mate,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )
        self.fields['cantMaterialesSeleccionados'] = forms.MultipleChoiceField(
            choices=cant,
            widget=forms.SelectMultiple(attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}),
            label='',
            required=True,
        )

        self.fields['estadoSolicitud'] = forms.ModelChoiceField(
            estadoDeSolicitud.objects,
            initial=actividad.estadoDeSolicitud.id,
            label=estadoDeSolicitud.objects.get(id=actividad.estadoDeSolicitud.id).descripcion,
            widget=forms.TextInput(
                attrs={'style': 'height: 1px; padding: 0; margin: 0; border: 0;'}
            ),
            required=False
        )

        self.fields['id'].initial = actividad.id


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

        try:
            del self.errors['sellosSeleccionados']
            del self.errors['materialesSeleccionados']
            del self.errors['ubiSellosSeleccionados']
            del self.errors['cantMaterialesSeleccionados']
        except:
            pass

        ts = self.data['tipoDeSolicitud']
        if ts == '11' or ts == '13':
            if not self.data['codigoDeCliente'].strip():
                self._errors["Cuenta"] = self.error_class([u"Ingrese un número de Cuenta."])
            if not self.data['serieRev'].strip():
                self._errors["Medidor"] = self.error_class([u"El Cliente debe tener un medidor activo."])
            if ts == '13':
                if not str(self.data['lecturaRev']).strip():
                    self._errors["Lectura"] = self.error_class([u"Ingrese una Lectura de Desconección "])
        if ts == '1' or ts == '13':
            if not self.data['tipoDeMedidor']:
                self._errors["Medidor"] = self.error_class([u" Seleccione el medidor a instalar "])
            if ts == '1':
                if not str(self.data['cuentaAnteriror']):
                    self._errors["Referencia"] = self.error_class(
                        [u"Ingrese la referencia de instalación del Servicio nuevo "])
                if len(str(self.data['nombreDeCliente']).split(' '))<2:
                    self._errors["Nombre del Cliente"] = self.error_class(
                        [u"Ingrese el nombre de cliente completo"])
                if len(str(self.data['direccionRef']).strip())<6:
                    self._errors["Direccion"] = self.error_class(
                        [u"Ingrese una direccion para referenciar la instalacion"])

        return cleaned_data
Example #14
0
class AutoForm(forms.Form):
    """Automatic translation form."""
    overwrite = forms.BooleanField(label=_('Overwrite strings'),
                                   required=False,
                                   initial=False)
    inconsistent = forms.BooleanField(label=_('Replace inconsistent'),
                                      required=False,
                                      initial=False)
    auto_source = forms.ChoiceField(
        label=_('Automatic translation source'),
        choices=[
            ('others', _('Other translation components')),
            ('mt', _('Machine translation')),
        ],
        initial='others',
    )
    subproject = forms.ChoiceField(label=_('Component to use'),
                                   required=False,
                                   initial='')
    engines = forms.MultipleChoiceField(
        label=_('Machine translation engines to use'),
        choices=[],
        required=False,
    )
    threshold = forms.IntegerField(
        label=_("Score threshold"),
        initial=80,
        min_value=1,
        max_value=100,
    )

    def __init__(self, obj, user, *args, **kwargs):
        """Generate choices for other subproject in same project."""
        other_subprojects = obj.subproject.project.subproject_set.exclude(
            id=obj.subproject.id)
        choices = [(s.id, force_text(s)) for s in other_subprojects]

        # Add components from other owned projects
        owned_components = SubProject.objects.filter(
            project__groupacl__groups__name__endswith='@Administration'
        ).exclude(project=obj.subproject.project).distinct()
        for component in owned_components:
            choices.append((component.id, force_text(component)))

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

        self.fields['subproject'].choices = \
            [('', _('All components in current project'))] + choices
        self.fields['engines'].choices = [
            (key, mt.name) for key, mt in MACHINE_TRANSLATION_SERVICES.items()
        ]
        if 'weblate' in MACHINE_TRANSLATION_SERVICES.keys():
            self.fields['engines'].initial = 'weblate'

        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            Field('overwrite'),
            Field('inconsistent'),
            InlineRadios('auto_source', id='select_auto_source'),
            Div('subproject', css_id='auto_source_others'),
            Div('engines', 'threshold', css_id='auto_source_mt'),
        )
class CheckboxChoicesForm(NgModelFormMixin, NgForm):
    scope_prefix = 'data'

    check_multi = forms.MultipleChoiceField(
        choices=[('a', 'Choice A'), ('b', 'Choice B'), ('c', 'Choice C')],
        widget=forms.CheckboxSelectMultiple,)
Example #16
0
class DocumentCreateForm(TranslationModelForm, DocumentFormMixin):
    """
    The document upload form.
    """
    permissions = forms.CharField(widget=HiddenInput(attrs={
        'name': 'permissions',
        'id': 'permissions'
    }),
                                  required=False)

    links = forms.MultipleChoiceField(label=_("Link to"), required=False)

    doc_file = SizeRestrictedFileField(label=_("File"),
                                       required=False,
                                       field_slug="document_upload_size")

    class Meta:
        model = Document
        fields = ['title', 'doc_file', 'doc_url']
        widgets = {
            'name': HiddenInput(attrs={
                'cols': 80,
                'rows': 20
            }),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['links'].choices = self.generate_link_choices()

    def clean_permissions(self):
        """
        Ensures the JSON field is JSON.
        """
        permissions = self.cleaned_data['permissions']

        if not self.fields['permissions'].required and (permissions is None
                                                        or permissions == ''):
            return None

        try:
            return json.loads(permissions)
        except ValueError:
            raise forms.ValidationError(_("Permissions must be valid JSON."))

    def clean(self):
        """
        Ensures the doc_file or the doc_url field is populated.
        """
        cleaned_data = super().clean()
        doc_file = self.cleaned_data.get('doc_file')
        doc_url = self.cleaned_data.get('doc_url')

        if not doc_file and not doc_url and "doc_file" not in self.errors and "doc_url" not in self.errors:
            logger.error("Document must be a file or url.")
            raise forms.ValidationError(_("Document must be a file or url."))

        if doc_file and doc_url:
            logger.error("A document cannot have both a file and a url.")
            raise forms.ValidationError(
                _("A document cannot have both a file and a url."))

        return cleaned_data

    def clean_doc_file(self):
        """
        Ensures the doc_file is valid.
        """
        doc_file = self.cleaned_data.get('doc_file')

        if doc_file and not os.path.splitext(doc_file.name)[1].lower(
        )[1:] in settings.ALLOWED_DOCUMENT_TYPES:
            logger.debug("This file type is not allowed")
            raise forms.ValidationError(_("This file type is not allowed"))

        return doc_file
Example #17
0
class TestForm(forms.Form):
    """Form with a variety of widgets to test bootstrap3 rendering."""

    date = forms.DateField(required=False)
    datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime(),
                                        required=False)
    subject = forms.CharField(
        max_length=100,
        help_text="my_help_text",
        required=True,
        widget=forms.TextInput(attrs={"placeholder": "placeholdertest"}),
    )
    password = forms.CharField(widget=forms.PasswordInput)
    message = forms.CharField(required=False, help_text="<i>my_help_text</i>")
    sender = forms.EmailField(label="Sender © unicode",
                              help_text='E.g., "*****@*****.**"')
    secret = forms.CharField(initial=42, widget=forms.HiddenInput)
    weird = forms.CharField(
        help_text="strings are now utf-8 \u03BCnico\u0394é!")
    cc_myself = forms.BooleanField(
        required=False,
        help_text=
        'cc stands for "carbon copy." You will get a copy in your mailbox.')
    select1 = forms.ChoiceField(choices=RADIO_CHOICES)
    select2 = forms.MultipleChoiceField(choices=RADIO_CHOICES,
                                        help_text="Check as many as you like.")
    select3 = forms.ChoiceField(choices=MEDIA_CHOICES)
    select4 = forms.MultipleChoiceField(choices=MEDIA_CHOICES,
                                        help_text="Check as many as you like.")
    category1 = forms.ChoiceField(choices=RADIO_CHOICES,
                                  widget=forms.RadioSelect)
    category2 = forms.MultipleChoiceField(
        choices=RADIO_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text="Check as many as you like.")
    category3 = forms.ChoiceField(widget=forms.RadioSelect,
                                  choices=MEDIA_CHOICES)
    category4 = forms.MultipleChoiceField(
        choices=MEDIA_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text="Check as many as you like.")
    number = forms.FloatField()
    url = forms.URLField()
    addon = forms.CharField(widget=forms.TextInput(attrs={
        "addon_before": "before",
        "addon_after": "after"
    }))

    # TODO: Re-enable this after Django 1.11 #28105 is available
    # polygon = gisforms.PointField()

    required_css_class = "bootstrap3-req"

    # Set this to allow tests to work properly in Django 1.10+
    # More information, see issue #337
    use_required_attribute = False

    def clean(self):
        cleaned_data = super().clean()
        raise forms.ValidationError(
            "This error was added to show the non field errors styling.")
        return cleaned_data
Example #18
0
class CategoryProductForm(forms.Form):
    primary_products = Select2MultipleField(
        label=_("Primary Category"),
        help_text=_(
            "Set this category as a primary category for selected products."),
        model=Product,
        required=False)
    additional_products = Select2MultipleField(
        label=_("Additional Category"),
        help_text=_("Add selected products to this category."),
        model=Product,
        required=False)
    remove_products = forms.MultipleChoiceField(
        label=_("Remove Products"),
        help_text=_("Remove selected products from this category."),
        required=False)

    def __init__(self, shop, category, **kwargs):
        self.shop = shop
        self.category = category
        super(CategoryProductForm, self).__init__(**kwargs)
        self.fields["remove_products"].choices = [(None, "-----")] + [
            (obj.product.pk, obj.product.name)
            for obj in category.shop_products.filter(shop=shop)
        ]

    @atomic
    def save(self):
        data = self.cleaned_data
        is_visible = self.category.status == CategoryStatus.VISIBLE
        visibility_groups = self.category.visibility_groups.all()
        primary_product_ids = [
            int(product_id) for product_id in data.get("primary_products", [])
        ]
        for shop_product in ShopProduct.objects.filter(
                Q(shop_id=self.shop.id),
                Q(product_id__in=primary_product_ids)
                | Q(product__variation_parent_id__in=primary_product_ids)):
            shop_product.primary_category = self.category
            shop_product.visibility = (ShopProductVisibility.ALWAYS_VISIBLE
                                       if is_visible else
                                       ShopProductVisibility.NOT_VISIBLE)
            shop_product.visibility_limit = self.category.visibility.value
            shop_product.visibility_groups = visibility_groups
            shop_product.save()
            shop_product.categories.add(self.category)

        additional_product_ids = [
            int(product_id)
            for product_id in data.get("additional_products", [])
        ]
        for shop_product in ShopProduct.objects.filter(
                Q(shop_id=self.shop.id),
                Q(product_id__in=additional_product_ids)
                | Q(product__variation_parent_id__in=additional_product_ids)):
            shop_product.categories.add(self.category)

        remove_product_ids = [
            int(product_id) for product_id in data.get("remove_products", [])
        ]
        for shop_product in ShopProduct.objects.filter(
                Q(product_id__in=remove_product_ids)
                | Q(product__variation_parent_id__in=remove_product_ids)):
            if shop_product.primary_category == self.category:
                if self.category in shop_product.categories.all():
                    shop_product.categories.remove(self.category)
                shop_product.primary_category = None
                shop_product.save()
            shop_product.categories.remove(self.category)
Example #19
0
class PreferencesForm(forms.Form):
    redirect_to = forms.CharField(required=False, widget=forms.HiddenInput)
    groups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                       required=False)
    syntax_highlighting = forms.BooleanField(
        required=False,
        label=_("Enable syntax highlighting in the diff viewer"))
    profile_private = forms.BooleanField(
        required=False, label=_("Keep your user profile private"))
    open_an_issue = forms.BooleanField(
        required=False, label=_("Always open an issue when comment box opens"))
    first_name = forms.CharField(required=False)
    last_name = forms.CharField(required=False)
    email = forms.EmailField()
    password1 = forms.CharField(required=False, widget=widgets.PasswordInput())
    password2 = forms.CharField(required=False, widget=widgets.PasswordInput())
    timezone = TimeZoneField(
        label=_("Time Zone"),
        required=True,
        help_text=_("The time zone used for this account."))

    def __init__(self, user, *args, **kwargs):
        from reviewboard.accounts.backends import get_auth_backends

        super(forms.Form, self).__init__(*args, **kwargs)

        auth_backends = get_auth_backends()
        choices = []

        for g in Group.objects.accessible(user=user).order_by('display_name'):
            choices.append((g.id, g.display_name))

        for site in user.local_site.all().order_by('name'):
            for g in Group.objects.accessible(
                    user=user, local_site=site).order_by('display_name'):
                display_name = '%s / %s' % (g.local_site.name, g.display_name)
                choices.append((g.id, display_name))

        self.fields['groups'].choices = choices
        self.fields['email'].required = auth_backends[0].supports_change_email

    def save(self, user):
        from reviewboard.accounts.backends import get_auth_backends

        auth_backends = get_auth_backends()
        primary_backend = auth_backends[0]

        password = self.cleaned_data['password1']

        if primary_backend.supports_change_password and password:
            primary_backend.update_password(user, password)

        if primary_backend.supports_change_name:
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
            primary_backend.update_name(user)

        if primary_backend.supports_change_email:
            user.email = self.cleaned_data['email']
            primary_backend.update_email(user)

        user.review_groups = self.cleaned_data['groups']
        user.save()

        profile = user.get_profile()
        profile.first_time_setup_done = True
        profile.syntax_highlighting = self.cleaned_data['syntax_highlighting']
        profile.is_private = self.cleaned_data['profile_private']
        profile.open_an_issue = self.cleaned_data['open_an_issue']
        profile.timezone = self.cleaned_data['timezone']
        profile.save()

    def clean_password2(self):
        p1 = self.cleaned_data['password1']
        p2 = self.cleaned_data['password2']
        if p1 != p2:
            raise forms.ValidationError('passwords do not match')
        return p2
Example #20
0
class RARequestForm(forms.ModelForm):
    person = PersonField(label='Appointee')
    supervisor = PersonField(label='Supervisor')

    ra_duties_ex = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_EX, widget=forms.CheckboxSelectMultiple,
                                             label="Experimental/Research Activities")
    ra_duties_dc = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_DC, widget=forms.CheckboxSelectMultiple,
                                             label="Data Collection/Analysis")
    ra_duties_pd = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_PD, widget=forms.CheckboxSelectMultiple,
                                             label="Project Development")
    ra_duties_im = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_IM, widget=forms.CheckboxSelectMultiple,
                                             label="Information Management")
    ra_duties_eq = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_EQ, widget=forms.CheckboxSelectMultiple,
                                             label="Equipment/Inventory Management and Development")
    ra_duties_su = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_SU, widget=forms.CheckboxSelectMultiple,
                                             label="Supervision")
    ra_duties_wr = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_WR, widget=forms.CheckboxSelectMultiple,
                                             label="Writing/Reporting")
    ra_duties_pm = forms.MultipleChoiceField(required=False, choices=DUTIES_CHOICES_PM, widget=forms.CheckboxSelectMultiple,
                                             label="Project Management")    

    people_comments = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3}), label="Any comments about the Appointee or Hiring Supervisor?")

    student = forms.ChoiceField(required=True, choices=STUDENT_TYPE, widget=forms.RadioSelect, label="Is the appointee a student?")
    coop = forms.ChoiceField(required=False, widget=forms.RadioSelect, choices=BOOL_CHOICES, label="Is the appointee a co-op student?")
    mitacs = forms.ChoiceField(required=False, widget=forms.RadioSelect, choices=BOOL_CHOICES, label="Is the appointee's co-op funded by a Mitacs scholarship in their own name?")
    thesis = forms.ChoiceField(required=False, widget=forms.RadioSelect, choices=BOOL_CHOICES, label="Is the appointment for the student's thesis/project?")

    fs1_unit = forms.IntegerField(required=True, label="Department #1", help_text="CS = 2110; ENSC = 2130; MSE = 2140; SEE = 2150; Dean's Office = 2010, 2020 or 2030")
    fs1_fund = forms.IntegerField(required=True, label="Fund #1", help_text="Example: 11, 13, 21, 31")
    fs1_project = forms.CharField(required=True, label="Project #1", help_text="Example: N654321, S654321, X654321, R654321. If fund 11 enter X000000")
    fs1_percentage = forms.IntegerField(required=False, label="Percentage of Funding Source #1 to Total Funding", help_text="Percentages of all funding sources must add up to 100.")

    fs2_option = forms.BooleanField(required=False, label="Please select the following if there is an additional funding source")
    fs2_unit = forms.IntegerField(required=False, label="Department #2", help_text="CS = 2110; ENSC = 2130; MSE = 2140; SEE = 2150; Dean's Office = 2010, 2020 or 2030")
    fs2_fund = forms.IntegerField(required=False, label="Fund #2", help_text="Example: 11, 13, 21, 31")
    fs2_project = forms.CharField(required=False, label="Project #2", help_text="Example: N654321, S654321, X654321, R654321. If fund 11 enter X000000")
    fs2_percentage = forms.IntegerField(required=False, label="Percentage of Funding Source #2 to Total Funding", help_text="Percentages of all funding sources must add up to 100.")

    fs3_option = forms.BooleanField(required=False, label="Please select the following if there is an additional funding source")
    fs3_unit = forms.IntegerField(required=False, label="Department #3", help_text="CS = 2110; ENSC = 2130; MSE = 2140; SEE = 2150; Dean's Office = 2010, 2020 or 2030")
    fs3_fund = forms.IntegerField(required=False, label="Fund #3", help_text="Example: 11, 13, 21, 31")
    fs3_project = forms.CharField(required=False, label="Percentage #3", help_text="Example: N654321, S654321, X654321, R654321. If fund 11 enter X000000")
    fs3_percentage = forms.IntegerField(required=False, label="Percentage of Funding Source #3 to Total Funding", help_text="Percentages of all funding sources must add up to 100.")

    gras_payment_method = forms.ChoiceField(required=False,
                                            choices=GRAS_PAYMENT_METHOD_CHOICES, 
                                            widget=forms.RadioSelect, 
                                            label="Scholarship (No added benefit & vacation cost)",
                                            help_text='Canadian bank status impacts how students will be paid. This generally applies to International' +
                                            'students currently working outside of Canada, who do not have banking status in Canada. If the status is' + 
                                            'unknown please confirm with the student.')
    ra_payment_method = forms.ChoiceField(required=False, choices=RA_PAYMENT_METHOD_CHOICES, widget=forms.RadioSelect, label="Please select from the following")

    rabw_total_gross = forms.DecimalField(required=False, label="Total Gross Salary Paid", max_digits=8, decimal_places=2)
    rabw_weeks_vacation = forms.DecimalField(required=False, label="Weeks Vacation (Minimum 2)", max_digits=8, decimal_places=1)
    rabw_biweekly_hours = forms.DecimalField(required=False, label="Bi-Weekly Hours", max_digits=8, decimal_places=1)
    rabw_biweekly_salary = forms.DecimalField(required=False, widget=forms.HiddenInput)
    rabw_gross_hourly = forms.DecimalField(required=False, widget=forms.HiddenInput)

    rah_gross_hourly = forms.DecimalField(required=False, label="Gross Hourly", max_digits=8, decimal_places=2)
    rah_vacation_pay = forms.DecimalField(required=False, label="Vacation Pay % (Minimum 4%)", max_digits=8, decimal_places=1)
    rah_biweekly_hours = forms.DecimalField(required=False, label="Bi-Weekly Hours", max_digits=8, decimal_places=2)

    grasls_total_gross = forms.DecimalField(required=False, label="Total Gross Salary Paid", max_digits=8, decimal_places=2)

    grasbw_total_gross = forms.DecimalField(required=False, label="Total Gross Salary Paid", max_digits=8, decimal_places=2)
    grasbw_biweekly_hours = forms.DecimalField(required=False, label="Bi-Weekly Hours", max_digits=8, decimal_places=1)
    grasbw_biweekly_salary = forms.DecimalField(required=False, widget=forms.HiddenInput)
    grasbw_gross_hourly = forms.DecimalField(required=False, widget=forms.HiddenInput)

    ra_benefits = forms.ChoiceField(required=False, choices=RA_BENEFITS_CHOICES, widget=forms.RadioSelect, label="Are you willing to provide extended health benefits?")

    funding_comments = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3}), label="Any comments about funding?")
    ra_other_duties = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3}), label="Other RA Duties")


    class Meta:
        model = RARequest
        exclude = ('config','deleted','status',) 
        labels = {
            'first_name': "Appointee First Name",
            'last_name': "Appointee Last Name",
            'email_address': "Appointee Email Address",
            'nonstudent': "Select if appointee does not have an ID",
            'department': "Appointee Department",
            'start_date': "Date Appointment Begins",
            'end_date': "Date Appointment Ends",
            'file_attachment_1': "Supplementary Document #1",
            'file_attachment_2': "Supplementary Document #2",
            }

        widgets = {
            'hiring_category': forms.HiddenInput(),
            'total_pay': forms.HiddenInput()     
        }

        help_texts = {
            'file_attachment_1': "Both of these fields are optional.",
            'file_attachment_2': "If co-op appointment, please upload co-op forms.",
        }

    def __init__(self, *args, **kwargs):
        super(RARequestForm, self).__init__(*args, **kwargs)
        not_required = ['person', 'nonstudent', 'first_name', 'last_name', 'email_address', 'file_attachment_1', 'file_attachment_2',
                    'ra_duties_ex', 'ra_duties_dc', 'ra_duties_pd', 'ra_duties_im', 'ra_duties_eq', 'ra_duties_su', 'ra_duties_wr', 
                    'ra_duties_pm', 'ra_other_duties']
        for field in not_required:
            self.fields[field].required = False   
        
        config_init = ['people_comments', 'coop', 'mitacs', 'student', 'thesis',
                'fs1_unit', 'fs1_fund', 'fs1_project', 'fs1_percentage',
                'fs2_option', 'fs2_unit', 'fs2_fund', 'fs2_project', 'fs2_percentage',
                'fs3_option', 'fs3_unit', 'fs3_fund', 'fs3_project', 'fs3_percentage',
                'rabw_total_gross', 'rabw_weeks_vacation', 'rabw_biweekly_salary', 'rabw_gross_hourly', 'rabw_biweekly_hours',
                'rah_gross_hourly', 'rah_vacation_pay', 'rah_biweekly_hours',
                'grasls_total_gross',
                'grasbw_total_gross', 'grasbw_gross_hourly', 'grasbw_biweekly_hours', 'grasbw_biweekly_salary',
                'ra_payment_method', 'gras_payment_method',
                'ra_benefits', 'funding_comments', 'ra_other_duties']

        for field in config_init:
            self.initial[field] = getattr(self.instance, field)

    def is_valid(self, *args, **kwargs):
        PersonField.person_data_prep(self)
        return super(RARequestForm, self).is_valid(*args, **kwargs)

    # TODO: Make sure total pay and hiring category are calculated properly. Javascript only for now.
    def clean(self):
        cleaned_data = super().clean()

        config_clean = ['people_comments', 'coop', 'mitacs', 'student', 'thesis',
                'fs1_unit', 'fs1_fund', 'fs1_project', 'fs1_percentage',
                'fs2_option', 'fs2_unit', 'fs2_fund', 'fs2_project', 'fs2_percentage',
                'fs3_option', 'fs3_unit', 'fs3_fund', 'fs3_project', 'fs3_percentage',
                'rabw_total_gross', 'rabw_weeks_vacation', 'rabw_biweekly_salary', 'rabw_gross_hourly', 'rabw_biweekly_hours',
                'rah_gross_hourly', 'rah_vacation_pay', 'rah_biweekly_hours',
                'grasls_total_gross',
                'grasbw_total_gross', 'grasbw_gross_hourly', 'grasbw_biweekly_hours', 'grasbw_biweekly_salary',
                'ra_payment_method', 'gras_payment_method',
                'ra_benefits', 'funding_comments', 'ra_other_duties']

        for field in config_clean:
            setattr(self.instance, field, cleaned_data[field])

        MIN_WAGE = 14.60
        MIN_WEEKS_VACATION = 2
        MIN_VACATION_PAY_PERCENTAGE = 4

        nonstudent = cleaned_data.get('nonstudent')
        first_name = cleaned_data.get('first_name')
        last_name = cleaned_data.get('last_name')
        email_address = cleaned_data.get('email_address')
        person = cleaned_data.get('person')

        # TODO: Why isn't this a required field regularly? Not in the list of non-required fields.
        if nonstudent:
            error_message = 'If the appointee does not have an SFU ID then you must answer this question.'       
            if first_name == None:
                self.add_error('first_name', error_message)
            if last_name == None:
                self.add_error('last_name', error_message)
            if email_address == None:
                self.add_error('email_address', error_message)
        else:
            if person == None:
                self.add_error('person', 'You must provide an SFU ID. If the appointee does not have an SFU ID, please select the checkbox below.')

        if nonstudent == None and person == None:
            raise forms.ValidationError("Cannot be a student and not have an SFU ID.")

        student = cleaned_data.get('student')
        coop = cleaned_data.get('coop')
        mitacs = cleaned_data.get('mitacs')
        thesis = cleaned_data.get('thesis')
        if student == 'U' or student == 'M' or student == 'P':
            error_message = 'If the appointee is a student then you must answer this question.'
            if coop == None:
                self.add_error('coop', error_message)
            if mitacs == None:
                self.add_error('mitacs', error_message)
        if mitacs == False:
            if thesis == None:
                self.add_error('thesis', 'You must answer this question.')

        fs2_option = cleaned_data.get('fs2_option')
        fs2_unit = cleaned_data.get('fs2_unit')
        fs2_fund = cleaned_data.get('fs2_fund')
        fs2_project = cleaned_data.get('fs2_project')

        if fs2_option:
            error_message = 'If you have a second funding source then you must answer this question.'
            if fs2_unit == None:
                self.add_error('fs2_unit', error_message)
            if fs2_fund == None:
                self.add_error('fs2_fund', error_message)
            if fs2_project == None or fs2_project == '':
                self.add_error('fs2_project', error_message)

        fs3_option = cleaned_data.get('fs3_option')
        fs3_unit = cleaned_data.get('fs3_unit')
        fs3_fund = cleaned_data.get('fs3_fund')
        fs3_project = cleaned_data.get('fs3_project')

        if fs3_option:
            error_message = 'If you have a third funding source then you must answer this question.'
            if fs3_unit == None:
                self.add_error('fs3_unit', error_message)
            if fs3_fund == None:
                self.add_error('fs3_fund', error_message)
            if fs3_project == None or fs2_project == '':
                self.add_error('fs3_project', error_message)

        fs1_percentage = cleaned_data.get('fs1_percentage')
        fs2_percentage = cleaned_data.get('fs2_percentage')
        fs3_percentage = cleaned_data.get('fs3_percentage')

        error_message = "Combined Percentages of all Funding Sources Must Add Up to 100%"
        if fs2_option and not fs3_option:
            percent_sum = fs1_percentage + fs2_percentage
            if percent_sum != 100:
                self.add_error('fs1_percentage', error_message)
                self.add_error('fs2_percentage', error_message)
        if fs2_option and fs3_option:
            percent_sum = fs1_percentage + fs2_percentage + fs3_percentage
            if percent_sum != 100:
                self.add_error('fs1_percentage', error_message)
                self.add_error('fs2_percentage', error_message)
                self.add_error('fs3_percentage', error_message)

        hiring_category = cleaned_data.get('hiring_category')

        gras_payment_method = cleaned_data.get('gras_payment_method')
        ra_payment_method = cleaned_data.get('ra_payment_method')

        if hiring_category == "RA":
            error_message = "Research Assistants must answer this question."
            if ra_payment_method == None or ra_payment_method == "":
                self.add_error('ra_payment_method', error_message)
        if hiring_category == "GRAS":
            error_message = "Graduate Research Assistants must answer this question."
            if gras_payment_method == None or gras_payment_method == "":
                self.add_error('gras_payment_method', error_message)

        grasbw_total_gross = cleaned_data.get('grasbw_total_gross')
        grasbw_biweekly_hours = cleaned_data.get('grasbw_biweekly_hours')
        grasls_total_gross = cleaned_data.get('grasls_total_gross')
        
        if gras_payment_method:
            error_message = "Graduate Research Assistants must answer this question."
            if gras_payment_method == "LS" or gras_payment_method == "LE":
                if grasls_total_gross == 0 or grasls_total_gross == None:
                    self.add_error('grasls_total_gross', error_message)
            if gras_payment_method == "BW":
                if grasbw_biweekly_hours == 0 or grasbw_biweekly_hours == None:
                    self.add_error('grasbw_biweekly_hours', error_message)
                if grasbw_total_gross == 0 or grasbw_total_gross == None:
                    self.add_error('grasbw_total_gross', error_message)
            if ra_payment_method:
                raise forms.ValidationError("Cannot be both an RA and a GRAS.")

        rabw_total_gross = cleaned_data.get('rabw_total_gross')
        rabw_weeks_vacation = cleaned_data.get('rabw_weeks_vacation')
        rabw_biweekly_hours = cleaned_data.get('rabw_biweekly_hours')
        rah_gross_hourly = cleaned_data.get('rah_gross_hourly')
        rah_vacation_pay = cleaned_data.get('rah_vacation_pay')
        rah_biweekly_hours = cleaned_data.get('rah_biweekly_hours')

        if ra_payment_method:
            error_message = "Research Assistants must answer this question."
            if ra_payment_method == "BW":
                if rabw_total_gross == 0 or rabw_total_gross == None:
                    self.add_error('rabw_total_gross', error_message)
                if rabw_weeks_vacation == None:
                    self.add_error('rabw_weeks_vacation', error_message)
                elif rabw_weeks_vacation < MIN_WEEKS_VACATION:
                    self.add_error('rabw_weeks_vacation', ('Weeks Vacation Must Be At Least ' + str(MIN_WEEKS_VACATION) + ' Weeks'))
                if rabw_biweekly_hours == None or rabw_biweekly_hours == 0:
                    self.add_error('rabw_biweekly_hours', error_message)
            if ra_payment_method == "H":
                if rah_gross_hourly == None:
                    self.add_error('rah_gross_hourly', error_message)
                elif rah_gross_hourly < MIN_WAGE:
                    self.add_error('rah_gross_hourly', ('Gross Hourly Must Be At Least Minimum Wage. (Currently: $' + str(MIN_WAGE) + ')'))
                if rah_vacation_pay == None:
                    self.add_error('rah_vacation_pay', error_message)
                elif rah_vacation_pay < MIN_VACATION_PAY_PERCENTAGE:
                    self.add_error('rah_vacation_pay', ('Vacation Pay Must Be At Least % ' + str(MIN_VACATION_PAY_PERCENTAGE)))
                if rah_biweekly_hours == None or rah_biweekly_hours == 0:
                    self.add_error('rah_biweekly_hours', error_message)

        start_date = cleaned_data.get('start_date')
        end_date = cleaned_data.get('end_date')
        if end_date < start_date:
            error_message = "Start date must be before end date."
            self.add_error('end_date', error_message)
            self.add_error('start_date', error_message)
Example #21
0
class Uploadform(forms.ModelForm):
    category=forms.MultipleChoiceField(choices = PCHOICES)
    class Meta:
        model = productImage
        fields = '__all__'
Example #22
0
 def get_fields(self, c, i):
     return [f.MultipleChoiceField(choices=c, initial=i)] + \
             [f.CharField() for _ in range(self.extra_inputs)]
Example #23
0
    def __init__(self, *args, **kwargs):
        """ Builds choices dynamically.
            <https://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field> """
        #
        super(SearchForm, self).__init__(*args, **kwargs)
        log.debug( 'SearchForm() instantiated' )
        log.debug( '*args, ```%s```' % args )
        log.debug( '**kwargs, ```%s```' % kwargs )
        #
        # url = 'https://127.0.0.1/test/dev/django_choices.json'
        # r = requests.get( url )
        # log.debug( 'r.content, ```%s```' % r.content )
        # self.choice_places = json.loads( r.content )
        #
        self.choice_places = [(item, item) for item in sorted( common.facetResults('placeMenu').keys()) if item]
        # self.fields['place'] = forms.MultipleChoiceField(required=False, choices=self.choice_places, widget=forms.SelectMultiple(attrs={'size':'10'}))
        self.fields['place'] = forms.MultipleChoiceField(required=False, choices=self.choice_places, widget=forms.CheckboxSelectMultiple())
        #
        self.vocab_request = requests.get("https://cds.library.brown.edu/projects/iip/include_taxonomies.xml")
        self.vocab = ET.fromstring(self.vocab_request.content)
        self.taxonomies = self.vocab.findall('{http://www.tei-c.org/ns/1.0}taxonomy')
        #
        log.debug( 'type(self.taxonomies), `%s`' % type(self.taxonomies) )
        log.debug( 'self.taxonomies[0].attrib.values(), ```%s```' % self.taxonomies[0].attrib.values() )
        log.debug( 'tax.attrib.values(), ```%s```' % [tax.attrib.values() for tax in self.taxonomies] )
        # self.type_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-genre'][0]
        self.type_tax = [tax for tax in self.taxonomies if list( tax.attrib.values() )[0] == 'IIP-genre'][0]
        # self.types_dict = dict([(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.type_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        #self.types_dict = dict([( list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text ) for element in self.type_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.types_dict = dict([(list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text.lstrip('-')) for element in self.type_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.choice_types = make_vocab_list( self.types_dict, sorted( common.facetResults('type').keys()) )
        # self.fields['type'] = forms.MultipleChoiceField(required=False, choices=self.choice_types, widget=forms.SelectMultiple(attrs={'size':'7'}))
        self.fields['type'] = forms.MultipleChoiceField(required=False, choices=self.choice_types, widget=forms.CheckboxSelectMultiple())
        #
        # self.phys_types_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-form'][0]
        self.phys_types_tax = [tax for tax in self.taxonomies if list( tax.attrib.values() )[0] == 'IIP-form'][0]
        # self.physical_types_dict = dict([(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.phys_types_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.physical_types_dict = dict([( list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text ) for element in self.phys_types_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.physical_types = make_vocab_list(self.physical_types_dict, sorted( common.facetResults('physical_type').keys()))
        # self.fields['physical_type'] = forms.MultipleChoiceField(required=False, choices=self.physical_types, widget=forms.SelectMultiple(attrs={'size':'7'}))
        self.fields['physical_type'] = forms.MultipleChoiceField(required=False, choices=self.physical_types, widget=forms.CheckboxSelectMultiple())
        #
        # self.religions_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-religion'][0]
        self.religions_tax = [tax for tax in self.taxonomies if list( tax.attrib.values() )[0] == 'IIP-religion'][0]
        # self.religions = [(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.religions_tax.findall('{http://www.tei-c.org/ns/1.0}category')]
        self.religions = [( list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text ) for element in self.religions_tax.findall('{http://www.tei-c.org/ns/1.0}category')]
        # self.fields['religion'] = forms.MultipleChoiceField(required=False, choices=self.religions, widget=forms.CheckboxSelectMultiple)
        self.fields['religion'] = forms.MultipleChoiceField(required=False, choices=self.religions, widget=forms.CheckboxSelectMultiple(attrs={'class': 'styled'}))
        #
        self.languages_dict = {
            "he":"Hebrew",
            "la": "Latin",
            "grc": "Greek",
            "arc": "Aramaic",
            "x-unknown":"Unknown"
            }
        self.languages = make_vocab_list(self.languages_dict, sorted( common.facetResults('language').keys()))
        # self.fields['language'] = forms.MultipleChoiceField(required=False, choices=self.languages, widget=forms.CheckboxSelectMultiple)
        self.fields['language'] = forms.MultipleChoiceField(required=False, choices=self.languages, widget=forms.CheckboxSelectMultiple())

        # self.material_tax = [tax for tax in self.taxonomies if tax.attrib.values()[0] == 'IIP-materials'][0]
        self.material_tax = [tax for tax in self.taxonomies if list(tax.attrib.values())[0] == 'IIP-materials'][0]
        # self.materials_dict = dict([(element.attrib.values()[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.material_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.materials_dict = dict([(list(element.attrib.values())[0], element.find('{http://www.tei-c.org/ns/1.0}catDesc').text) for element in self.material_tax.findall('{http://www.tei-c.org/ns/1.0}category')])
        self.materials = make_vocab_list( self.materials_dict, sorted( common.facetResults('material').keys()) )
        self.fields['material'] = forms.MultipleChoiceField(required=False, choices=self.materials, widget=forms.CheckboxSelectMultiple())
Example #24
0
class SearchFilterForm(forms.Form):
    CHOICES_NEIGHBOURHOOD = [
        ("Chelsea and Clinton", "Chelsea and Clinton"),
        ("Lower East Side", "Lower East Side"),
        ("Gramercy Park and Murray Hill", "Gramercy Park and Murray Hill"),
        ("Greenwich Village and Soho", "Greenwich Village and Soho"),
        ("Upper West Side", "Upper West Side"),
        ("Central Harlem", "Central Harlem"),
        ("Upper East Side", "Upper East Side"),
        ("East Harlem", "East Harlem"),
        ("Inwood and Washington Heights", "Inwood and Washington Heights"),
        ("Lower Manhattan", "Lower Manhattan"),
        ("Stapleton and St. George", "Stapleton and St. George"),
        ("Tribeca", "Tribeca"),
        ("Port Richmond", "Port Richmond"),
        ("South Shore", "South Shore"),
        ("Mid-Island", "Mid-Island"),
        ("High Bridge and Morrisania", "High Bridge and Morrisania"),
        ("Central Bronx", "Central Bronx"),
        ("Hunts Point and Mott Haven", "Hunts Point and Mott Haven"),
        ("Bronx Park and Fordham", "Bronx Park and Fordham"),
        ("Southeast Bronx", "Southeast Bronx"),
        ("Northeast Bronx", "Northeast Bronx"),
        ("Kingsbridge and Riverdale", "Kingsbridge and Riverdale"),
        ("Southeast Queens", "Southeast Queens"),
        ("Northwest Queens", "Northwest Queens"),
        ("Long Island City", "Long Island City"),
        ("Northwest Brooklyn", "Northwest Brooklyn"),
        ("Bushwick and Williamsburg", "Bushwick and Williamsburg"),
        ("East New York and New Lots", "East New York and New Lots"),
        ("Southwest Brooklyn", "Southwest Brooklyn"),
        ("Flatbush", "Flatbush"),
        ("Greenpoint", "Greenpoint"),
        ("Central Brooklyn", "Central Brooklyn"),
        ("Borough Park", "Borough Park"),
        ("Sunset Park", "Sunset Park"),
        ("Bushwick and Williamsburg", "Bushwick and Williamsburg"),
        ("Southern Brooklyn", "Southern Brooklyn"),
        ("Canarsie and Flatlands", "Canarsie and Flatlands"),
        ("North Queens", "North Queens"),
        ("Northeast Queens", "Northeast Queens"),
        ("Central Queens", "Central Queens"),
        ("West Queens", "West Queens"),
        ("West Central Queens", "West Central Queens"),
        ("Southeast Queens", "Southeast Queens"),
        ("Jamaica", "Jamaica"),
        ("Southwest Queens", "Southwest Queens"),
        ("Rockaways", "Rockaways"),
    ]
    CHOICES_CATEGORY = [
        ("newamerican", "newamerican"),
        ("armenian", "armenian"),
        ("barbeque", "barbeque"),
        ("bars", "bars"),
        ("bistros", "bistros"),
        ("burgers", "burgers"),
        ("chinese", "chinese"),
        ("danish", "danish"),
        ("diners", "diners"),
        ("ethiopian", "ethiopian"),
        ("filipino", "filipino"),
        ("french", "french"),
        ("georgian", "georgian"),
        ("german", "german"),
        ("greek", "greek"),
        ("hotdog", "hotdog"),
        ("italian", "italian"),
        ("bistros", "bistros"),
        ("japanese", "japanese"),
        ("jewish", "jewish"),
        ("kebab", "kebab"),
        ("korean", "korean"),
        ("kosher", "kosher"),
        ("mexican", "mexican"),
        ("noodles", "noodles"),
        ("pizza", "pizza"),
        ("salad", "salad"),
        ("sandwiches", "sandwiches"),
        ("seafood", "seafood"),
        ("sushi", "sushi"),
        ("tapassmallplates", "tapassmallplates"),
        ("vegan", "vegan"),
        ("vegetarian", "vegetarian"),
        ("vietnamese", "vietnamese"),
        ("waffles", "waffles"),
        ("wraps", "wraps"),
    ]

    CHOICES_RATING = [("5", "5"), ("4", "4"), ("3", "3"), ("2", "2"),
                      ("1", "1")]

    CHOICES_SORT = [
        ("none", "none"),
        ("recommended", "recommended"),
        ("ratedhigh", "ratedhigh"),
        ("ratedlow", "ratedlow"),
        ("pricehigh", "pricehigh"),
        ("pricelow", "pricelow"),
    ]

    keyword = forms.CharField(label="keyword", required=False)
    neighbourhood = forms.MultipleChoiceField(label="neighbourhood",
                                              choices=CHOICES_NEIGHBOURHOOD,
                                              required=False)
    category = forms.MultipleChoiceField(label="category",
                                         choices=CHOICES_CATEGORY,
                                         required=False)

    form_sort = forms.ChoiceField(label="form_sort",
                                  choices=CHOICES_SORT,
                                  required=False)

    price_1 = forms.BooleanField(label="price_1", required=False)
    price_2 = forms.BooleanField(label="price_2", required=False)
    price_3 = forms.BooleanField(label="price_3", required=False)
    price_4 = forms.BooleanField(label="price_4", required=False)

    All = forms.BooleanField(label="All", required=False)
    COVIDCompliant = forms.BooleanField(label="COVID-19 Compliant",
                                        required=False)
    MOPDCompliant = forms.BooleanField(label="MOPD Compliant", required=False)

    fav = forms.BooleanField(label="fav", required=False)

    rating = forms.MultipleChoiceField(label="rating",
                                       choices=CHOICES_RATING,
                                       required=False)

    def clean_keyword(self):
        keyword = self.cleaned_data.get("keyword")
        if keyword == "":
            return None
        return keyword

    def clean_neighbourhood(self):
        neighbourhood = self.cleaned_data.get("neighbourhood")
        # Check if Empty list
        if neighbourhood is not None and len(neighbourhood) == 0:
            return None
        return neighbourhood

    def clean_category(self):
        category = self.cleaned_data.get("category")
        if category is not None and len(category) == 0:
            return None
        return category

    def get_price_filter(self):
        price_filter = []
        if self.cleaned_data.get("price_1"):
            price_filter.append("$")
        if self.cleaned_data.get("price_2"):
            price_filter.append("$$")
        if self.cleaned_data.get("price_3"):
            price_filter.append("$$$")
        if self.cleaned_data.get("price_4"):
            price_filter.append("$$$$")
        return price_filter

    def get_rating_filter(self):
        rating_filter = []
        if self.cleaned_data.get("rating"):
            for rating in self.cleaned_data.get("rating"):
                rating_filter.append(rating)
                rating_filter.append(str(float(rating) - 0.5))
        return rating_filter

    def get_compliant_filter(self):
        compliant_filter = []
        if self.cleaned_data.get("All"):
            return None
        if self.cleaned_data.get("COVIDCompliant"):
            compliant_filter.append("COVIDCompliant")
        if self.cleaned_data.get("MOPDCompliant"):
            compliant_filter.append("MOPDCompliant")
        return compliant_filter
Example #25
0
 class TagForm(forms.Form):
     questions = forms.MultipleChoiceField(
         choices=[(q.pk, q.text) for q in Question.objects.all()])
     tag = forms.ChoiceField(
         choices=[(t.pk, t.name) for t in Tag.objects.all().exclude(
             name__in=['qotd', 'quest', 'challenge'])])
Example #26
0
class QueueSearchForm(happyforms.Form):
    text_query = forms.CharField(
        required=False,
        label=_(u'Search by add-on name / author email'))
    searching = forms.BooleanField(widget=forms.HiddenInput, required=False,
                                   initial=True)
    admin_review = forms.ChoiceField(required=False,
                                     choices=[('', ''),
                                              ('1', _(u'yes')),
                                              ('0', _(u'no'))],
                                     label=_(u'Admin Flag'))
    application_id = forms.ChoiceField(
        required=False,
        label=_(u'Application'),
        choices=([('', '')] +
                 [(a.id, a.pretty) for a in amo.APPS_ALL.values()]))
    addon_type_ids = forms.MultipleChoiceField(
        required=False,
        label=_(u'Add-on Types'),
        choices=((id, tp) for id, tp in amo.ADDON_TYPES.items()))

    def __init__(self, *args, **kw):
        super(QueueSearchForm, self).__init__(*args, **kw)

    def clean_addon_type_ids(self):
        if self.cleaned_data['addon_type_ids']:
            # Remove "Any Addon Extension" from the list so that no filter
            # is applied in that case.
            ids = set(self.cleaned_data['addon_type_ids'])
            self.cleaned_data['addon_type_ids'] = ids - set(str(amo.ADDON_ANY))
        return self.cleaned_data['addon_type_ids']

    def filter_qs(self, qs):
        data = self.cleaned_data
        if data['admin_review']:
            qs = qs.filter(admin_review=data['admin_review'])
        if data['addon_type_ids']:
            qs = qs.filter_raw('addon_type_id IN', data['addon_type_ids'])
        if data['application_id']:
            qs = qs.filter_raw('apps_match.application_id =',
                               data['application_id'])
            # We join twice so it includes all apps, and not just the ones
            # filtered by the search criteria.
            app_join = ('LEFT JOIN applications_versions apps_match ON '
                        '(versions.id = apps_match.version_id)')
            qs.base_query['from'].extend([app_join])

        if data['text_query']:
            lang = get_language()
            joins = [
                'LEFT JOIN addons_users au on (au.addon_id = addons.id)',
                'LEFT JOIN users u on (u.id = au.user_id)',
                """LEFT JOIN translations AS supportemail_default ON
                        (supportemail_default.id = addons.supportemail AND
                         supportemail_default.locale=addons.defaultlocale)""",
                """LEFT JOIN translations AS supportemail_local ON
                        (supportemail_local.id = addons.supportemail AND
                         supportemail_local.locale=%%(%s)s)""" %
                qs._param(lang),
                """LEFT JOIN translations AS ad_name_local ON
                        (ad_name_local.id = addons.name AND
                         ad_name_local.locale=%%(%s)s)""" %
                qs._param(lang)]
            qs.base_query['from'].extend(joins)
            fuzzy_q = u'%' + data['text_query'] + u'%'
            qs = qs.filter_raw(
                Q('addon_name LIKE', fuzzy_q) |
                # Search translated add-on names / support emails in
                # the editor's locale:
                Q('ad_name_local.localized_string LIKE', fuzzy_q) |
                Q('supportemail_default.localized_string LIKE', fuzzy_q) |
                Q('supportemail_local.localized_string LIKE', fuzzy_q) |
                Q('au.role IN', [amo.AUTHOR_ROLE_OWNER,
                                 amo.AUTHOR_ROLE_DEV],
                  'u.email LIKE', fuzzy_q))
        return qs
Example #27
0
class SolicitudesForm(forms.Form):

	PROFESION_CHOICES = (
		('N', 'No Aplica'),
		('P', 'Primaria'),
		('B', 'Bachiller'),
		('S', 'Tecnico Superior'),
		('U', 'Universitaria')
		)

	nombre = forms.CharField(max_length=12, label="Nombre")
	snombre = forms.CharField(max_length=12, required=False, label="Segundo Nombre")
	apellido = forms.CharField(max_length=15, label="Apellido")
	sapellido = forms.CharField(max_length=15, required=False, label="Segundo Apellido")
	cedula = forms.CharField(max_length=8, required=True, label="Cedula")
	fecha_nacimiento = forms.DateTimeField(label="Fecha de Nacimiento", widget=SelectDateWidget, required=False)
	tel1 = forms.CharField(max_length=11, label="Telefono Celular")
	tel2 = forms.CharField(max_length=11, required=False, label="Telefono Fijo")
	cotizacion = forms.ChoiceField(choices=SINO_CHOICES, label="Cotiza FAOV", widget=forms.RadioSelect)
	profesion = forms.ChoiceField(choices=PROFESION_CHOICES)
	email = forms.EmailField(max_length=42, label="Correo Electronico")
	observaciones = forms.CharField(max_length=400, initial="No hay observaciones", widget=forms.Textarea)
	SERVICIOS_CHOICES = (
		('AP', 'Agua Potable'),
		('AS', 'Agua Servida'),
		('E', 'Electricidad'),
		('G', 'Gas'),
		('V', 'Vialidad'),
		('T', 'Telefonia'),
	)
	posesion = forms.ChoiceField(choices=SINO_CHOICES)
	servicios = forms.MultipleChoiceField(SERVICIOS_CHOICES)
	tenencia = forms.ChoiceField(choices=SINO_CHOICES)
	ESTADO_CHOICES = (
		('AM', 'Amazonas'),
		('AZ', 'Anzoategui'),
		('AP', 'Apure'),
		('AR', 'Aragua'),
		('BA', 'Barinas'),
		('BO', 'Bolivar'),
		('CA', 'Carabobo'),
		('CO', 'Cojedes'),
		('DA', 'Delta Amacuro'),
		('DC', 'Distrito Capital'),
		('FA', 'Falcon'),
		('GU', 'Guarico'),
		('LA', 'Lara'),
		('ME', 'Merida'),
		('MI', 'Miranda'),
		('MO', 'Monagas'),
		('NE', 'Nueva Esparta'),
		('PO', 'Portuguesa'),
		('SU', 'Sucre'),
		('TA', 'Tachira'),
		('TR', 'Trujillo'),
		('VA', 'Vargas'),
		('YA', 'Yaracuy'),
		('ZU', 'Zulia'),
		)
	estado = forms.ChoiceField(ESTADO_CHOICES)
	municipio = forms.CharField()
	parroquia = forms.CharField()
	sector = forms.CharField(max_length=150)
	calle = forms.CharField(max_length=20, label="Av./Calle")
	casa = forms.CharField(max_length=20, label="Edificio/Casa")
	ncasa = forms.CharField(max_length=4, label="N Casa/Apartamento")
class SelectMultipleChoicesForm(NgModelFormMixin, NgForm):
    scope_prefix = 'form_data'

    select_multi = forms.MultipleChoiceField(
        choices=[('a', 'Choice A'), ('b', 'Choice B'), ('c', 'Choice C')])
Example #29
0
    def __init__(self, *args, **kwargs):
        event = self.event = kwargs.pop('event')
        super().__init__(*args, **kwargs)

        recp_choices = [('orders', _('Everyone who created a ticket order'))]
        if event.settings.attendee_emails_asked:
            recp_choices += [
                ('attendees',
                 _('Every attendee (falling back to the order contact when no attendee email address is '
                   'given)')),
                ('both',
                 _('Both (all order contact addresses and all attendee email addresses)'
                   ))
            ]
        self.fields['recipients'].choices = recp_choices

        self.fields['subject'] = I18nFormField(
            label=_('Subject'),
            widget=I18nTextInput,
            required=True,
            locales=event.settings.get('locales'),
        )
        self.fields['message'] = I18nFormField(
            label=_('Message'),
            widget=I18nTextarea,
            required=True,
            locales=event.settings.get('locales'),
        )
        self._set_field_placeholders('subject',
                                     ['event', 'order', 'position_or_address'])
        self._set_field_placeholders('message',
                                     ['event', 'order', 'position_or_address'])
        choices = [(e, l) for e, l in Order.STATUS_CHOICE if e != 'n']
        choices.insert(0, ('na', _('payment pending (except unapproved)')))
        choices.insert(0, ('pa', _('approval pending')))
        if not event.settings.get('payment_term_expire_automatically',
                                  as_type=bool):
            choices.append(('overdue', _('pending with payment overdue')))
        self.fields['sendto'] = forms.MultipleChoiceField(
            label=_("Send to customers with order status"),
            widget=forms.CheckboxSelectMultiple(
                attrs={'class': 'scrolling-multiple-choice no-search'}),
            choices=choices)
        if not self.initial.get('sendto'):
            self.initial['sendto'] = ['p', 'na']
        elif 'n' in self.initial['sendto']:
            self.initial['sendto'].append('pa')
            self.initial['sendto'].append('na')

        self.fields['items'].queryset = event.items.all()
        if not self.initial.get('items'):
            self.initial['items'] = event.items.all()

        self.fields['checkin_lists'].queryset = event.checkin_lists.all()
        self.fields['checkin_lists'].widget = Select2Multiple(
            attrs={
                'data-model-select2':
                'generic',
                'data-select2-url':
                reverse('control:event.orders.checkinlists.select2',
                        kwargs={
                            'event': event.slug,
                            'organizer': event.organizer.slug,
                        }),
                'data-placeholder':
                _('Send to customers checked in on list'),
            })
        self.fields['checkin_lists'].widget.choices = self.fields[
            'checkin_lists'].choices
        self.fields['checkin_lists'].label = _(
            'Send to customers checked in on list')

        if event.has_subevents:
            self.fields['subevent'].queryset = event.subevents.all()
            self.fields['subevent'].widget = Select2(
                attrs={
                    'data-model-select2':
                    'event',
                    'data-select2-url':
                    reverse('control:event.subevents.select2',
                            kwargs={
                                'event': event.slug,
                                'organizer': event.organizer.slug,
                            }),
                    'data-placeholder':
                    pgettext_lazy('subevent', 'Date')
                })
            self.fields['subevent'].widget.choices = self.fields[
                'subevent'].choices
        else:
            del self.fields['subevent']
            del self.fields['subevents_from']
            del self.fields['subevents_to']
Example #30
0
class BlenderForm(forms.Form):
    sounds = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['sounds'].choices = Sound.objects.values_list('pk', 'sign')