def __init__(self, *args, **kwargs):
		"""
		highlighted - touples to show as radio buttons
		"""
	
		self.highlighted = []
		if "highlighted" in kwargs:
			self.highlighted = kwargs.pop("highlighted")
		Select.__init__(self, *args, **kwargs)
Esempio n. 2
0
 def get_form(self, request, obj=None, **kwargs):
     form = super().get_form(request, obj, **kwargs)
     form.base_fields['entity_type'].widget = Select(choices=(('party',
                                                               'party'), ))
     return form
Esempio n. 3
0
    entries = LogEntry.objects.filter(date__gte=since)
    # Get post url and title
    entries = entries.values(
        'post__id',
        'post__title',
        'post__url',
        'post__slug',
        'post__blog__user__id',
        'post__blog__user__hacker__avatar_url',
        'post__blog__stream',
    )
    # Count the visits
    entries = entries.annotate(total=Count('post__id'))
    # Get top 'n' posts
    entries = entries.order_by('total').reverse()[:n]
    return entries


def _get_tsv(entry):
    return u'{post__id}\t{post__title}\t{post__url}\t{total}'.format(**entry)


BlogForm = modelform_factory(
    Blog,
    fields=("feed_url", "stream"),
    widgets={
        'feed_url': TextInput(attrs={'class': 'form-control', 'type': 'url'}),
        'stream': Select(attrs={'class': 'custom-select'}),
    },
)
Esempio n. 4
0
class PodcastForm(BetterModelForm):
    """
    Start with the common fields
    """
    title = CharField(
        label='Title',
        widget=TextInput(attrs={
            'class': 'input',
            'type': 'text',
            'placeholder': 'Podcast Title'
        }))

    slug = CharField(label='Slug',
                     widget=TextInput(attrs={
                         'class': 'input slug',
                         'type': 'text'
                     }),
                     help_text='Only letters, numbers, and -')

    subtitle = CharField(
        label='Subtitle',
        required=False,
        widget=TextInput(attrs={
            'class': 'input',
            'type': 'text',
            'placeholder': 'Podcast Subtitle'
        }))

    description = CharField(
        label='Description',
        required=False,
        widget=MarkdownWidget(attrs={
            'class': 'input textarea',
            'type': 'text',
            'rows': 6
        }))

    language = ChoiceField(label='Language',
                           widget=Select(attrs={'class': 'input inline'}),
                           choices=LANGUAGE_CHOICES)

    explicit = ChoiceField(label='Contains Explicit Material',
                           widget=Select(attrs={'class': 'input inline'}),
                           choices=EXPLICIT_CHOICES,
                           initial=EXPLICIT_CHOICES[1][0])

    tags = CharField(label='Tags',
                     required=False,
                     widget=TextInput(
                         attrs={
                             'class': 'input',
                             'type': 'text',
                             'placeholder': 'Comma-separated list of tags.'
                         }))

    itunes_categories = ModelMultipleChoiceField(
        queryset=Category.objects.annotate(num_cats=Count('category')).filter(
            num_cats__lt=1).order_by('parent'),
        label='iTunes Categories',
        required=False,
        widget=SelectMultiple(attrs={
            'class': 'input taller',
            'size': 10
        }))

    author = CharField(label='Author Name',
                       widget=TextInput(attrs={
                           'class': 'input',
                           'type': 'text'
                       }))

    contact = CharField(label='Author Email',
                        widget=EmailInput(attrs={
                            'class': 'input',
                            'type': 'email'
                        }))

    image = FileField(label='Podcast Image',
                      required=False,
                      widget=FileInput(attrs={
                          'class': 'input',
                          'type': 'file'
                      }),
                      help_text='Minimum 1400x1400 RGB PNG or JPEG')

    website = CharField(label='Podcast Website',
                        required=False,
                        widget=TextInput(attrs={
                            'class': 'input',
                            'type': 'url'
                        }),
                        help_text="URL to this podcast's home page")

    credits = CharField(label='Art and Music Credits',
                        required=False,
                        widget=MarkdownWidget(attrs={
                            'class': 'input textarea',
                            'type': 'text',
                            'rows': 6
                        }),
                        help_text='One contributer per line.')

    frequency = ChoiceField(label='Publishing Frequency',
                            widget=Select(attrs={'class': 'input'}),
                            choices=FREQUENCY_CHOICES)

    license = ChoiceField(label='License',
                          widget=Select(attrs={'class': 'input'}),
                          choices=LICENSE_CHOICES)

    feed_format = ChoiceField(label='Feed Type',
                              widget=Select(attrs={'class': 'input'}),
                              choices=FEED_TYPE_CHOICES,
                              initial=FEED_TYPE_CHOICES[1][0],
                              help_text='Type of feed to publish.')

    organization = CharField(label='Organization',
                             required=False,
                             widget=TextInput(attrs={
                                 'class': 'input',
                                 'type': 'text'
                             }))

    station = CharField(label='Radio Station',
                        required=False,
                        widget=TextInput(attrs={
                            'class': 'input',
                            'type': 'text'
                        }))

    copyright = CharField(label='Copyright',
                          required=False,
                          widget=TextInput(attrs={'class': 'input'}))

    ttl = IntegerField(label='Minutes this feed can be cached',
                       initial=1440,
                       widget=TextInput(attrs={'class': 'input'}))

    max_age = IntegerField(
        label='Days to keep an episode (set to 0 to keep forever)',
        initial=0,
        widget=TextInput(attrs={'class': 'input'}))

    editor_name = CharField(label='Editor Name',
                            required=False,
                            widget=TextInput(attrs={'class': 'input'}))

    editor_email = CharField(label='Editor Email',
                             required=False,
                             widget=TextInput(attrs={'class': 'input'}))

    webmaster_name = CharField(label='Webmaster name',
                               required=False,
                               widget=TextInput(attrs={'class': 'input'}))

    webmaster_email = CharField(label='Webmaster Email',
                                required=False,
                                widget=TextInput(attrs={'class': 'input'}))

    block = ChoiceField(label='Block',
                        widget=Select(attrs={'class': 'input inline'}),
                        choices=BOOLEAN_CHOICES,
                        initial=BOOLEAN_CHOICES[0][0],
                        help_text='Disable this podcast in iTunes.')

    rename_files = ChoiceField(
        label='Rename Files',
        widget=Select(attrs={'class': 'input inline'}),
        choices=BOOLEAN_CHOICES,
        initial=BOOLEAN_CHOICES[0][0],
        help_text='Rename audio files with slug and date.')

    tag_audio = ChoiceField(
        label='Tag Audio',
        widget=Select(attrs={'class': 'input inline'}),
        choices=BOOLEAN_CHOICES,
        initial=BOOLEAN_CHOICES[1][0],
        help_text='Tag audio file with podcast/episode details.')

    pub_url = CharField(label='Publication (rss) URL',
                        required=False,
                        widget=TextInput(attrs={'class': 'input'}))

    storage_url = CharField(label='File Storage URL',
                            required=False,
                            widget=TextInput(attrs={'class': 'input'}))

    itunes_url = CharField(label='iTunes URL',
                           required=False,
                           widget=TextInput(attrs={'class': 'input'}))

    feedburner_url = CharField(label='FeedBurner URL',
                               required=False,
                               widget=TextInput(attrs={'class': 'input'}))

    tmp_dir = CharField(label='Temporary Directory',
                        initial='/tmp',
                        widget=TextInput(attrs={'class': 'input'}))

    up_dir = CharField(label='Upload Directory',
                       required=False,
                       widget=TextInput(attrs={'class': 'input'}))

    cleaner = CharField(label='Cleaner',
                        required=False,
                        widget=TextInput(attrs={'class': 'input'}))

    combine_segments = ChoiceField(
        label='Combine Segments',
        widget=Select(attrs={'class': 'input inline'}),
        choices=BOOLEAN_CHOICES,
        initial=BOOLEAN_CHOICES[0][0])

    publish_segments = ChoiceField(
        label='Publish Segments',
        widget=Select(attrs={'class': 'input inline'}),
        choices=BOOLEAN_CHOICES,
        initial=BOOLEAN_CHOICES[0][0])

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

        category_choices = []

        for category in Category.objects.all():
            new_category = []
            sub_categories = []

            if not category.parent:
                if len(category.category_set.all()) > 0:
                    for sub_category in category.category_set.all():
                        sub_categories.append(
                            [sub_category.id, sub_category.name])
                    new_category = [category.name, sub_categories]
                else:
                    new_category = [category.id, category.name]
                category_choices.append(new_category)

        self.fields['itunes_categories'].choices = category_choices

    class Meta:
        model = Podcast

        fieldsets = [('main', {
            'fields': [
                'title', 'slug', 'subtitle', 'description', 'author',
                'contact', 'image', 'frequency', 'language', 'explicit',
                'itunes_categories', 'tags', 'copyright', 'license'
            ],
            'legend':
            'Required Settings',
            'classes': ['required', 'drawer', 'active']
        }),
                     ('Optional', {
                         'fields': [
                             'editor_name', 'editor_email', 'organization',
                             'website', 'station', 'credits', 'feedburner_url',
                             'webmaster_name', 'webmaster_email', 'block',
                             'rename_files', 'tag_audio', 'itunes_url'
                         ],
                         'legend':
                         'Optional Settings',
                         'classes': ['optional', 'collapse']
                     }),
                     ('Advanced', {
                         'fields': [
                             'feed_format', 'ttl', 'max_age', 'pub_url',
                             'storage_url', 'tmp_dir', 'combine_segments',
                             'publish_segments', 'up_dir', 'cleaner'
                         ],
                         'legend':
                         'Advanced Settings',
                         'description':
                         """Don't change these unless you know
                                   what you are doing.""",
                         'classes': ['advanced', 'collapse']
                     })]
    def __init__(self, *args, **kwargs):
        """
        Retrieves initial data for diagnosis category choices during form creation. However, data is retrieved from
        [data] instead of [initial] in kwargs after performing form validation
        :param args:    variable arguments
        :param kwargs:  named arguments
        """

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

        log_start_time()

        choice_list = None

        logger.info('Setting default label and widget for value and remark fields')
        self.fields['value'].label = ''
        self.fields['remark'].label = ''
        self.fields['value'].widget = NonInputWidget()
        self.fields['remark'].widget = NonInputWidget()

        logger.info('Retrieving diagnosis category')
        if kwargs.get('data'):
            logger.info('Performing initial form creation')
            diagnosis_category = DiagnosisCategory.objects.get(
                pk=kwargs.get('data')['%s-diagnosis_category' % kwargs.get('prefix')])
        elif kwargs.get('initial'):
            logger.info('Performed form validation')
            diagnosis_category = kwargs.get('initial')['diagnosis_category']
        else:
            logger.warn('Did not receive value for required diagnosis_category parameter')
            diagnosis_category = None

        if diagnosis_category:
            logger.info('Setting label for value field using [%s]' % diagnosis_category)
            self.fields['value'].label = diagnosis_category

            logger.info('Instantiating form helper for [%s]' % diagnosis_category)
            self.helper = DiagnosisCategoryFormHelper(diagnosis_category)

            logger.info('Retrieving choices from database for [%s]' % diagnosis_category)
            choice_list = DiagnosisCategoryChoice.objects.filter(
                diagnosis_category=diagnosis_category).order_by('order')
        else:
            logger.warn('diagnosis_category is none or empty')

        if choice_list:
            logger.info(
                'Creating dropdown widget for value field using retrieved choices for [%s]' % diagnosis_category)
            self.fields['value'].widget = Select(choices=list(choice_list.values_list('description',
                                                                                      'description')))

            logger.info('Checking if list for [%s] contains a general term' % diagnosis_category)
            for choice in choice_list:
                if choice.is_general_term:
                    logger.info('Setting CSS class and widget for [%s]' % choice)
                    self.fields['remark'].widget = Textarea(
                        attrs={'placeholder': 'Additional Information', 'style': 'height: 5em;', })
                else:
                    pass
        else:
            logger.info('No choice list found for [%s]' % diagnosis_category)

        log_end_time()
Esempio n. 6
0
class VerificacionFiltersForm(Form):
    TYPES = (
        ('+', 'CREACIÓN'),
        ('~', 'EDICIÓN'),
        ('-', 'BORRADO'),

    )
    equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm', 'required': 'required'}
        )
    )
    tipo_equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm'}
        )
    )
    fecha_inicio = CharField(
        widget=TextInput(
            attrs={'class': 'form-control input-sm', 'required': 'required'})
    )
    fecha_fin = CharField(
        widget=TextInput(
            attrs={'class': 'form-control input-sm', 'required': 'required'})
    )
    tipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm'})
    )
    history_type = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm'}
        )
    )

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

        super(VerificacionFiltersForm, self).__init__(*args, **kwargs)
        self.fields['tipo_equipo'].choices = self.get_TiposEquipo()
        self.fields['tipo'].choices = self.get_Tipos()
        self.fields['history_type'].choices = self.get_HistoryType(self.TYPES)
        self.fields['history_type'].label = "Operación"

    def clean_equipo(self):
        data = self.cleaned_data['equipo']
        if data == 0:
            raise ValidationError("Debe seleccionar un equipo")
        else:
            return data

    def get_TiposEquipo(self):

        tipo = []

        registros = TipoEquipo.objects.all()

        for registro in registros:
            tipo.append(
                (
                    registro.pk,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return tipo

    def get_Odometros(self):

        odometro = []

        registros = Odometro.objects.all()

        for registro in registros:
            odometro.append(
                (
                    registro.id,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return odometro

    def get_Tipos(self):

        tipo = [('0', '--------')]

        registros = TipoOdometro.objects.all()

        for registro in registros:
            tipo.append(
                (
                    registro.id,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return tipo

    def get_HistoryType(self, _opciones):
        opciones = [('', '-------')]

        for registro in _opciones:
            opciones.append(registro)
        return opciones
Esempio n. 7
0
class MedicionFiltersForm(Form):

    equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm', 'multiple': 'multiple'}
        )
    )
    odometro = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm', 'multiple': 'multiple'}
        )
    )
    fecha_inicio = CharField(
        widget=TextInput(
            attrs={'class': 'form-control input-sm', 'required': 'required', 'data-date-format': 'yyyy-mm-dd'})
    )
    fecha_fin = CharField(
        widget=TextInput(
            attrs={'class': 'form-control input-sm', 'required': 'required', 'data-date-format': 'yyyy-mm-dd'})
    )
    tipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm'})
    )

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

        super(MedicionFiltersForm, self).__init__(*args, **kwargs)
        self.fields['equipo'].choices = self.get_Equipos()
        self.fields['odometro'].choices = self.get_Odometros()
        self.fields['tipo'].choices = self.get_Tipos()

    def get_Equipos(self):

        equipo = []

        registros = Equipo.objects.all()

        for registro in registros:
            equipo.append(
                (
                    registro.pk,
                    "(%s) %s " % (registro.tag, registro.descripcion)
                )
            )

        return equipo

    def get_Odometros(self):

        odometro = []

        registros = Odometro.objects.all()

        for registro in registros:
            odometro.append(
                (
                    registro.id,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return odometro

    def get_Tipos(self):

        tipo = [('0', '--------')]

        registros = TipoOdometro.objects.all()

        for registro in registros:
            tipo.append(
                (
                    registro.id,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return tipo
Esempio n. 8
0
class SeguimientoComprasFilterForm(Form):
    TIPOS_REQUISISION = (('', '-------'), ('SR',
                                           'SR - Requisición de Servicios'),
                         ('OR', 'OR - Requisición de Materiales'),
                         ('XR', 'XR - Requisición de Activos'),
                         ('SJ', 'SJ - Requisición de JackUp'),
                         ('1N', '1N - Requisición para compra Nacional'),
                         ('1P', '1P - Requisición para compra Nacional Rel'),
                         ('1I', '1I - Requisición para compra de Importacion'),
                         ('1Q',
                          '1Q - Requisición para compra de Importacion Rel'))
    TIPOS_COTIZACION = (('', '-------'), ('QS', 'QS - Cotización de Servicio'),
                        ('OQ', 'OQ - Cotización de Materiales'),
                        ('QX', 'QX - Cotización de Activos'),
                        ('QJ', 'QJ - Cotización de JackUp'),
                        ('2N', '2N - Cotizacion para compra Nacional'),
                        ('2P', '2P - Cotizacion para compra Nacional Rel'),
                        ('2I', '2I - Cotizacion para compra de Importacion'),
                        ('2Q',
                         '2Q - Cotizacion para compra de Importacion Rel'))
    TIPOS_OC = (('', '-------'), ('OS', 'OS - OC de Servicio'),
                ('OP', 'OP - OC de Materiales'), ('OX', 'OX - OC de Activos'),
                ('OJ',
                 'OJ - OC de JackUp'), ('3N',
                                        '3N - Orden para compra Nacional'),
                ('3P', '3P - Orden para compra Nacional Rel'),
                ('3I', '3I - Orden para compra de Importacion'),
                ('3Q', '3Q - Orden para compra de Importacion Rel'))

    CANCELADAS = (
        ('-980', 'No mostrar canceladas'),
        ('', 'Mostrar canceladas'),
        ('980', 'Solo canceladas'),
    )
    RECEPCION = (('', '-------'), ('COMPLETA', 'Con recepción'),
                 ('PENDIENTE', 'Sin recepción'), ('PARCIAL', 'Parcial'))

    compania = ChoiceField(widget=Select(attrs={
        'name': 'compania',
        'class': 'select2 nova-select2'
    }))
    sucursal = ChoiceField(label="Sucursal/Planta",
                           widget=Select(attrs={
                               'name': 'sucursal',
                               'class': 'select2 nova-select2'
                           }))
    comprador = CharField(label="Comprador Nombre",
                          widget=TextInput(
                              attrs={
                                  'name': 'comprador',
                                  'class': 'form-control input-xs',
                                  'placeholder': 'Ejemplo: JORDAN'
                              }))

    requisicion = IntegerField(
        label="Requisicion No.",
        widget=NumberInput(attrs={
            'name': 'requisicion',
            'class': 'form-control input-xs',
            'min': '1'
        }))
    requisicion_tipo = CharField(label="Requisicion Tipo",
                                 widget=Select(attrs={
                                     'name': 'requisicion_tipo',
                                     'class': 'form-control input-xs'
                                 },
                                               choices=TIPOS_REQUISISION))
    requisicion_originador = ChoiceField(
        label="Requisicion Originador",
        widget=Select(attrs={
            'name': 'requisicion_originador',
            'class': 'select2 nova-select2'
        }))
    requisicion_canceladas = CharField(
        label='¿Mostrar canceladas?',
        widget=Select(attrs={'class': 'select2 nova-select2'},
                      choices=CANCELADAS))
    requisicion_desde = CharField(widget=TextInput(
        attrs={
            'class': 'form-control input-xs',
            'readonly': 'readonly'
        }))

    requisicion_hasta = CharField(widget=TextInput(
        attrs={
            'class': 'form-control input-xs',
            'readonly': 'readonly'
        }))

    cotizacion = IntegerField(
        label="Cotizacion No.",
        widget=NumberInput(attrs={
            'name': 'cotizacion',
            'class': 'form-control input-xs',
            'min': '1'
        }))
    cotizacion_tipo = CharField(label="Cotizacion Tipo",
                                widget=Select(attrs={
                                    'name': 'cotizacion_tipo',
                                    'class': 'form-control input-xs'
                                },
                                              choices=TIPOS_COTIZACION))
    cotizacion_originador = ChoiceField(
        label="Cotizacion Originador",
        widget=Select(attrs={
            'name': 'cotizacion_originador',
            'class': 'select2 nova-select2'
        }))
    cotizacion_canceladas = CharField(
        label='¿Mostrar canceladas?',
        widget=Select(attrs={'class': 'select2 nova-select2'},
                      choices=CANCELADAS))

    oc = IntegerField(
        label="Orden No.",
        widget=NumberInput(attrs={
            'name': 'oc',
            'class': 'form-control input-xs',
            'min': '1'
        }))
    oc_tipo = CharField(label="Orden Tipo",
                        widget=Select(attrs={
                            'name': 'oc_tipo',
                            'class': 'form-control input-xs'
                        },
                                      choices=TIPOS_OC))
    oc_originador = ChoiceField(
        label="Orden Originador",
        widget=Select(attrs={
            'name': 'oc_originador',
            'class': 'select2 nova-select2'
        }))
    oc_canceladas = CharField(label='¿Mostrar canceladas?',
                              widget=Select(
                                  attrs={'class': 'select2 nova-select2'},
                                  choices=CANCELADAS))
    oc_desde = CharField(widget=TextInput(
        attrs={
            'class': 'form-control input-xs',
            'readonly': 'readonly'
        }))
    oc_hasta = CharField(widget=TextInput(
        attrs={
            'class': 'form-control input-xs',
            'readonly': 'readonly'
        }))

    proveedor = CharField(label="Proveedor Nombre",
                          widget=TextInput(
                              attrs={
                                  'name': 'proveedor',
                                  'class': 'form-control input-xs',
                                  'placeholder': 'Ejemplo: SANTANDREU'
                              }))
    item = CharField(label="Articulo descripcion",
                     widget=TextInput(
                         attrs={
                             'name': 'item',
                             'class': 'form-control input-xs',
                             'placeholder': 'Ejemplo: TUBERIA'
                         }))
    recepcion = CharField(widget=Select(attrs={
        'name': 'recepcion',
        'class': 'form-control input-xs'
    },
                                        choices=RECEPCION))

    def __init__(self, *args, **kwargs):
        super(SeguimientoComprasFilterForm, self).__init__(*args, **kwargs)
        self.fields['compania'].choices = self.get_Compania()
        self.fields['sucursal'].choices = self.get_Sucursal()
        self.fields['requisicion_originador'].choices = self.get_Originador()
        self.fields['cotizacion_originador'].choices = self.get_Originador()
        self.fields['oc_originador'].choices = self.get_Originador()

    def get_Compania(self):

        valores = [('', '-------')]

        companias = VIEW_COMPANIAS.objects.using('jde_p').all()

        for compania in companias:

            valores.append((
                compania.comp_code,
                str(int(compania.comp_code)) + ' - ' + compania.comp_desc,
            ))
        return valores

    def get_Sucursal(self):

        valores = [('', '-------')]

        unidades = VIEW_UNIDADES.objects.using('jde_p').all()

        for unidad in unidades:

            valores.append((
                unidad.clave,
                '(' + unidad.clave + ')' + ' ' + unidad.desc_corta,
            ))
        return valores

    def get_Originador(self):
        valores = [('', '-------')]
        originadores = VIEW_USUARIOS.objects.using('jde_p').filter(
            dir_tipo__contains="E")

        for originador in originadores:
            valores.append((
                originador.clave,
                originador.dir_desc,
            ))
        return valores
Esempio n. 9
0
class OutcomeForm(ModelForm):

    semester = ChoiceField(choices=Outcome.SEMESTER_CHOICES,
        widget = Select(attrs={
            'id': 'outcome_semester',
            'class': 'form-control custom-select select-fix-height',
            'name': 'semester',
        }),
        required=False,
    )
    year = ChoiceField(choices=YEAR_CHOICES,
        widget = Select(attrs={
            'id': 'outcome_year',
            'class': 'form-control custom-select select-fix-height',
            'name': 'year',
        }),
        required=False,
    )
    section = ChoiceField(
        widget = Select(attrs={
            'id': 'outcome_course_section',
            'class': 'form-control custom-select select-fix-height',
            'name': 'section',
        }),
        required=False,
    )
    course = ModelChoiceField(queryset=None,
        widget = Select(attrs={
            'id': 'outcome_course',
            'class': 'form-control select-fix-height',
            'name': 'course',
        }),
        required=False,
        empty_label="Select a course"
    )

    class Meta:
        model = Outcome
        fields = (
            'course',
            'section',
            'description',
            'semester',
            'year',
            'is_public',
            'title', 
        )

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(OutcomeForm, self).__init__(*args, **kwargs)
 
        if user.is_superuser:
            self.fields['course'].queryset = Course.objects.extra(
                select={'course_number': "CAST(substring(number FROM '^[0-9]+') AS INTEGER)"}
                ).order_by('subject','course_number')
        else:
            self.fields['course'].queryset = user.staffprofile.courses.all()

        self.fields['title'].widget = TextInput(attrs={
            'id': 'outcome_title',
            'class': 'form-control',
            'name': 'title',
            'maxlength': '99',
        })
        self.fields['description'].widget = Textarea(attrs={
            'id': 'outcome_description',
            'class': 'form-control',
            'name': 'description',
            'maxlength': '2000',
        })

        section_choices = []
        course_id = None
        if 'course' in self.initial:
            course_id = self.initial.get('course')
        elif 'course' in self.data and self.data['course']:
            course_id = self.data.get('course')
        elif self.instance.pk and self.instance.course:
            course_id = self.instance.course.pk

        if course_id != None:
            course = Course.objects.get(pk=course_id)
            section_choices += BLANK_CHOICE_DASH
            for section in course.sections:
                section_choices.append((section, "{:02d}".format(section)))
            self.fields['section'].choices = section_choices
        else:
            self.fields['section'].disabled = True


    def clean_year(self):
        year = self.cleaned_data.get('year')
        if year:
            return year
        return None

    def clean_section(self):
        section = self.cleaned_data.get('section')
        if section:
            return section
        return None
Esempio n. 10
0
    def __init__(self, *args, **kwargs):
        super(BaseOutcomeMediaUpdateFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.fields['outcome_type'].choices = OutcomeMedia.UNPRIVILEGED_OUTCOME_TYPES


OutcomeMediaFormSet = inlineformset_factory(
    Outcome, OutcomeMedia,
    formset=BaseOutcomeMediaFormSet,
    fields=('media', 'outcome_type'),
    extra=1,
    validate_max=True,
    
    widgets={
        'media': MediaClearableFileInput(attrs={'multiple': True}),
        'outcome_type': Select(attrs={'class': 'form-control select-fix-height'}),
    }
)

OutcomeMediaDirectoryFormSet = inlineformset_factory(
    Outcome, OutcomeMedia,
    formset=BaseOutcomeMediaFormSet,
    fields=('media', 'outcome_type'),
    extra=1,
    validate_max=True,
    widgets={
        'media': MediaClearableFileInput(attrs={'webkitdirectory': True, 'mozdirectory': True}),
        'outcome_type': Select(attrs={'class': 'form-control select-fix-height'})
    }
)
Esempio n. 11
0
 class CopyForm(Form):
     degree = IntegerField(widget=Select(
         choices=((1, gettext_lazy('test')), )))
Esempio n. 12
0
 class Meta:
     model = User
     fields = ('email', 'ime', 'prezime', 'tip', 'godina')
     widgets = {'tip': Select(attrs={"onChange": 'myFunction()'})}
Esempio n. 13
0
    def render_widget_values(self, request):
        # TODO: Cleanup this hog of a method

        def merge_attrs(attrs_1, attrs_2):
            for key, value in attrs_2.items():
                if key in attrs_1 and key == 'class':
                    attrs_1[key] += ' %s' % attrs_2[key]
                else:
                    attrs_1[key] = attrs_2[key]
            return attrs_1

        attrs = {'class': 'valuefield form-control'}

        value = request.GET.get("value", "")
        key_id = request.GET.get("key_id", "")
        operation = request.GET.get("operation", "")
        field = None
        value = value and value.split(",") or []
        widget = TextInput().render(request.GET.get("name", ""),
                                    ",".join(value),
                                    attrs=attrs)

        # Get widget if there's no form field
        if key_id == 'activity_identifier':
            if operation in ("in", "not_in"):
                widget = TextInput().render(request.GET.get("name", ""),
                                            ",".join(value),
                                            attrs=attrs)
            else:
                widget = NumberInput().render(request.GET.get("name", ""),
                                              ",".join(value),
                                              attrs=attrs)
        elif key_id == "fully_updated" or key_id == "last_modification":
            value = len(value) > 0 and value[0] or ""
            if value:
                try:
                    value = datetime.strptime(value, "%Y-%m-%d")
                except ValueError:
                    value = ""
            widgetObject = DateTimePicker(options={
                "format": "YYYY-MM-DD",
                "inline": True,
            })

            # See here: https://github.com/jorgenpt/django-bootstrap3-datetimepicker/commit/042dd1da3a7ff21010c1273c092cba108d95baeb#commitcomment-16877308
            widgetObject.js_template = """<script>
                    $(function(){$("#%(picker_id)s:has(input:not([readonly],[disabled]))").datetimepicker(%(options)s);});
            </script>"""
            widget = widgetObject.render(
                request.GET.get("name", ""),
                value=value,
                attrs={"id": "id_%s" % request.GET.get("name", "")})

        elif key_id == "fully_updated_by":
            users = User.objects.filter(
                groups__name__in=("Research admins",
                                  "Research assistants")).order_by("username")
            if operation in ("in", "not_in"):
                widget = SelectMultiple(
                    choices=[(u.id, u.get_full_name() or u.username)
                             for u in users]).render(
                                 request.GET.get("name", ""),
                                 value,
                                 attrs={
                                     "id":
                                     "id_%s" % request.GET.get("name", ""),
                                     "class": "form-control"
                                 })
            else:
                widget = Select(choices=[(u.id,
                                          u.get_full_name() or u.username)
                                         for u in users]).render(
                                             request.GET.get("name", ""),
                                             len(value) == 1 and value[0]
                                             or value,
                                             attrs={
                                                 "id":
                                                 "id_%s" %
                                                 request.GET.get("name", "")
                                             })
        # Deprecated?
        if "inv_" in key_id:
            field = get_field_by_key(key_id[4:])
        else:
            field = get_field_by_key(key_id)

        # Get widget by form field
        if field:
            widget = field.widget
            attrs = merge_attrs(attrs, field.widget.attrs)
            attrs["id"] = "id_%s" % request.GET.get("name", "")
            if widget.attrs.get("readonly", ""):
                del widget.attrs["readonly"]
            if type(widget) == HiddenInput:
                field.widget = Select(choices=field.choices)
                widget = Select(choices=field.choices)
            if type(widget) == LocationWidget:
                field.widget = TextInput()
                widget = field.widget.render(request.GET.get("name", ""),
                                             len(value) > 0 and value[0] or "",
                                             attrs=attrs)
            elif operation in ("in", "not_in"):
                if type(widget) == YearBasedSelect:
                    field.widget = YearBasedMultipleSelect(
                        choices=field.widget.choices)
                    # FIXME: multiple value parameters can arrive like "value=1&value=2" or "value=1,2", not very nice
                    value = type(value) in (
                        list, tuple) and value or request.GET.getlist(
                            "value", [])
                    value = [value, ""]
                    widget = field.widget.render(request.GET.get("name", ""),
                                                 value,
                                                 attrs=attrs)

                elif type(widget) == YearBasedTextInput:
                    widget = widget.render(request.GET.get("name", ""),
                                           ",".join(value),
                                           attrs=attrs)
                elif type(widget) == RadioSelect:
                    widget = CheckboxSelectMultiple()
                    widget.choices = field.widget.choices
                    widget = widget.render(request.GET.get("name", ""), value)
                elif issubclass(type(field.widget),
                                (CheckboxSelectMultiple, SelectMultiple)):
                    widget = widget.render(request.GET.get("name", ""), value)
                elif isinstance(widget, Select):
                    widget = SelectMultiple()
                    widget.choices = field.widget.choices
                    widget = widget.render(request.GET.get("name", ""), value)
                else:
                    widget = widget.render(request.GET.get("name", ""),
                                           ",".join(value),
                                           attrs=attrs)
            elif operation in ("contains", ):
                widget = TextInput().render(request.GET.get("name", ""),
                                            ",".join(value),
                                            attrs=attrs)
            else:
                if issubclass(
                        type(field.widget),
                    (CheckboxSelectMultiple, SelectMultiple, RadioSelect)):
                    widget = widget.render(request.GET.get("name", ""), value)
                elif issubclass(
                        type(field.widget),
                    (YearBasedMultipleSelect, YearBasedSelect,
                     YearBasedTextInput, YearBasedSelectMultipleNumber)):
                    widget = widget.render(request.GET.get("name", ""),
                                           ",".join(value),
                                           attrs=attrs)
                else:
                    widget = widget.render(request.GET.get("name", ""),
                                           ",".join(value),
                                           attrs=attrs)

        return HttpResponse(widget, content_type="text/plain")
Esempio n. 14
0
 class Meta:
     model = Member
     fields = ('title', 'grad')
     widgets = {'title': Select(), 'grad': Select()}
Esempio n. 15
0
def is_select(field):
    return field.field.widget.__class__.__name__ == Select().__class__.__name__
Esempio n. 16
0
 class Meta:
     model = UserProfile
     fields = ('phone', 'address', 'city', 'country', 'image')
     widgets = {
         'city': Select(attrs={'placeholder': 'city'}, choices=CITY)
     }
Esempio n. 17
0
 class Meta:
     model = SocialDemographicData
     fields = [
         'natural_of', 'citizenship', 'profession', 'occupation', 'tv',
         'dvd', 'radio', 'bath', 'automobile', 'wash_machine',
         'refrigerator', 'freezer', 'house_maid', 'religion', 'payment',
         'flesh_tone', 'patient_schooling', 'schooling',
         'benefit_government', 'social_class'
     ]
     widgets = {
         'natural_of':
         TextInput(attrs={'class': 'form-control'}),
         'citizenship':
         SelectBoxCountries(attrs={'data-flags': 'true'}),
         'patient_schooling':
         Select(attrs={'class': 'form-control'}),
         'schooling':
         Select(attrs={'class': 'form-control'}),
         'flesh_tone':
         Select(attrs={'class': 'form-control'}),
         'religion':
         Select(attrs={'class': 'form-control'}),
         'profession':
         TextInput(attrs={
             'class': 'form-control',
             'placeholder': _('Type in profession')
         }),
         'occupation':
         TextInput(attrs={
             'class': 'form-control',
             'placeholder': _('Inform occupation')
         }),
         'payment':
         Select(attrs={'class': 'form-control'}),
         'tv':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'dvd':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'radio':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'bath':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'automobile':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'house_maid':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'wash_machine':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'refrigerator':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'freezer':
         RadioSelect(choices=((0, '0'), (1, '1'), (2, '2'), (3, '3'),
                              (4, _('4 or +')))),
         'social_class':
         TextInput(attrs={
             'class': 'form-control',
             'readonly': ""
         })
     }
Esempio n. 18
0
class OdometroFiltersForm(Form):

    clave = CharField(
        widget=TextInput(attrs={'class': 'form-control input-sm'})
    )
    descripcion = CharField(
        widget=TextInput(attrs={'class': 'form-control input-sm'})
    )
    udm = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm  select2'}
        )
    )
    equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm  select2'}
        )
    )
    tipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm  select2'}
        )
    )
    acumulado = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm  select2'}
        )
    )

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

        super(OdometroFiltersForm, self).__init__(*args, **kwargs)
        self.fields['equipo'].choices = self.get_Equipos()
        self.fields['udm'].choices = self.get_Udm()
        self.fields['tipo'].choices = self.get_Tipos()
        self.fields['acumulado'].choices = self.get_Acumulado(Odometro.ACUMULADO)

    def get_Equipos(self):

        equipo = [('', '-------')]

        registros = Equipo.objects.all()

        for registro in registros:
            equipo.append(
                (
                    registro.pk,
                    "(%s) %s" % (registro.tag, registro.descripcion)
                )
            )

        return equipo

    def get_Udm(self):

        udm = [('', '-------')]

        registros = UdmOdometro.objects.all()

        for registro in registros:
            udm.append(
                (
                    registro.id,
                    "(%s) %s" % (registro.clave, registro.descripcion)
                )
            )

        return udm

    def get_Tipos(self):

        tipo = [('', '-------')]

        registros = TipoOdometro.objects.all()

        for registro in registros:
            tipo.append(
                (
                    registro.id,
                    "(%s) %s" % (registro.clave, registro.descripcion)
                )
            )

        return tipo

    def get_Acumulado(self, _opciones):
        opciones = [('', '-------')]

        for registro in _opciones:
            opciones.append(registro)
        return opciones
Esempio n. 19
0
    class Meta:
        model = Patient

        fields = [
            'anonymous', 'name', 'cpf', 'origin', 'medical_record',
            'date_birth', 'gender', 'rg', 'marital_status', 'country',
            'zipcode', 'street', 'address_number', 'address_complement',
            'district', 'city', 'state', 'email'
        ]

        widgets = {
            'name':
            TextInput(
                attrs={
                    'class': 'form-control',
                    'autofocus': "true",
                    'required': "",
                    'data-error': _('Name must be included')
                }),
            'cpf':
            TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'xxx.xxx.xxx-xx'
            }),
            'origin':
            TextInput(attrs={'class': 'form-control'}),
            'medical_record':
            TextInput(attrs={'class': 'form-control'}),
            'date_birth':
            DateInput(format=_("%m/%d/%Y"),
                      attrs={
                          'class': 'form-control datepicker',
                          'required': "",
                          'placeholder': _('mm/dd/yyyy'),
                          'data-error': _('Date of birth must be completed')
                      }),
            'gender':
            Select(
                attrs={
                    'class': 'form-control',
                    'required': "",
                    'data-error': _('Gender must be filled')
                }),
            'rg':
            TextInput(attrs={'class': 'form-control'}),
            'marital_status':
            Select(attrs={'class': 'form-control'}),
            'country':
            SelectBoxCountries(attrs={'data-flags': 'true'}),
            'zipcode':
            CEPInput(address={
                'street': 'id_street',
                'district': 'id_district',
                'city': 'id_city',
                'state': 'id_state'
            },
                     attrs={
                         'class': 'form-control',
                         'pattern': '\d{5}-?\d{3}'
                     }),
            'street':
            TextInput(attrs={'class': 'form-control'}),
            'address_number':
            TextInput(attrs={'class': 'form-control'}),
            'address_complement':
            TextInput(attrs={'class': 'form-control'}),
            'district':
            TextInput(attrs={'class': 'form-control'}),
            'city':
            TextInput(attrs={'class': 'form-control'}),
            'state':
            SelectBoxState(attrs={'data-country': 'id_country'}),
            'email':
            TextInput(
                attrs={
                    'class':
                    'form-control',
                    'type':
                    'email',
                    'data-error':
                    _('Incorrect e-mail'),
                    'pattern':
                    '^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$'
                }),
        }
Esempio n. 20
0
class CapturaFiltersForm(Form):

    equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm', 'required': 'required'}
        )
    )
    tipo_equipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm'}
        )
    )
    fecha_inicio = CharField(
        widget=TextInput(
            attrs={'class': 'form-control input-sm', 'required': 'required', 'data-date-format': 'yyyy-mm-dd'})
    )
    fecha_fin = CharField(
        widget=TextInput(
            attrs={'class': 'form-control input-sm', 'required': 'required', 'data-date-format': 'yyyy-mm-dd'})
    )
    tipo = ChoiceField(
        widget=Select(
            attrs={'class': 'form-control input-sm'})
    )

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

        super(CapturaFiltersForm, self).__init__(*args, **kwargs)
        # self.fields['equipo'].choices = self.get_Equipos()
        self.fields['tipo_equipo'].choices = self.get_TiposEquipo()
        self.fields['tipo'].choices = self.get_Tipos()

    def clean_equipo(self):
        data = self.cleaned_data['equipo']
        if data == 0:
            raise ValidationError("Debe seleccionar un equipo")
        else:
            return data

    def get_TiposEquipo(self):

        tipo = []

        registros = TipoEquipo.objects.all()

        for registro in registros:
            tipo.append(
                (
                    registro.pk,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return tipo

    def get_Odometros(self):

        odometro = []

        registros = Odometro.objects.all()

        for registro in registros:
            odometro.append(
                (
                    registro.id,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return odometro

    def get_Tipos(self):

        tipo = [('0', '--------')]

        registros = TipoOdometro.objects.all()

        for registro in registros:
            tipo.append(
                (
                    registro.id,
                    "(%s) %s " % (registro.clave, registro.descripcion)
                )
            )

        return tipo
Esempio n. 21
0
 class Meta:
     model = OrganizationPublicProfile
     fields = [
         'org_structure',
         'primary_audience',
         'ownership',
         'business_model',
         'unionized_workforce',
         'diversity',
         'special_skills',
         'good_partner',
         'best_coverage',
         'collab_experience',
         'platform_print',
         'platform_online',
         'platform_social',
         'platform_network_tv',
         'platform_cable_tv',
         'platform_radio',
         'platform_podcast',
         'platform_newsletter',
         'platform_streaming_video',
     ]
     widgets = {
         'org_structure':
         Select(attrs={
             'class': 'custom-select',
             'id': 'org_structure'
         }),
         'primary_audience':
         TextInput(attrs={
             'class': 'form-control',
             'placeholder': 'Audience'
         }),
         'ownership':
         TextInput(attrs={
             'class': 'form-control',
             'placeholder': 'Ownership Structure'
         }),
         'business_model':
         TextInput(attrs={
             'class': 'form-control',
             'placeholder': 'Business Model'
         }),
         'unionized_workforce':
         TextInput(
             attrs={
                 'class': 'form-control',
                 'placeholder': 'Unionization of workforce'
             }),
         'collab_experience':
         TextInput(
             attrs={
                 'class': 'form-control',
                 'placeholder': 'Experience with Collaboration'
             }),
         'diversity':
         Textarea(
             attrs={
                 'class': 'form-control',
                 'placeholder':
                 'How does your organization foster diversity?'
             }),
         'special_skills':
         Textarea(
             attrs={
                 'class': 'form-control',
                 'placeholder':
                 'Special skills or strengths in the newsroom'
             }),
         'good_partner':
         Textarea(
             attrs={
                 'class': 'form-control',
                 'placeholder':
                 'What makes your organization a good partner'
             }),
         'best_coverage':
         Textarea(
             attrs={
                 'class':
                 'form-control',
                 'placeholder':
                 'What coverage is your organizatino most proud of?'
             }),
     }
Esempio n. 22
0
 class Meta:
     model = empresas
     fields = [
         'barrio', 'fechacenso', 'nombre', 'identificacion', 'direccion',
         'propietario', 'email', 'telefono', 'fecharegistro', 'actividad',
         'regimen', 'naturaleza', 'stiker', 'ica', 'observaciones', 'fotos'
     ]
     widgets = {
         'barrio':
         Select(attrs={'class': 'form-control'}),
         'fechacenso':
         DateInput(attrs={
             'class': 'form-control',
             'type': 'date'
         }),
         'nombre':
         TextInput(attrs={'class': 'form-control'}),
         'identificacion':
         TextInput(attrs={'class': 'form-control'}),
         'direccion':
         TextInput(attrs={'class': 'form-control'}),
         'propietario':
         TextInput(attrs={'class': 'form-control'}),
         'email':
         EmailInput(attrs={'class': 'form-control'}),
         'telefono':
         NumberInput(attrs={'class': 'form-control'}),
         'fecharegistro':
         DateInput(attrs={
             'class': 'form-control',
             'type': 'date'
         }),
         'actividad':
         Select(attrs={'class': 'form-control'}),
         'regimen':
         Select(attrs={'class': 'form-control'}),
         'naturaleza':
         Select(attrs={'class': 'form-control'}),
         'stiker':
         NumberInput(attrs={'class': 'form-control'}),
         'ica':
         CheckboxInput(attrs={'class': 'form-control'}),
         'observaciones':
         TextInput(attrs={'class': 'form-control'}),
         'fotos':
         FileInput(attrs={'class': 'form-control'}),
     }
     labels = {
         'barrio': 'Barrio',
         'fechacenso': 'Fecha del censo',
         'nombre': 'Nombre comercial',
         'identificacion': 'C.C. o NIT',
         'direccion': 'Dirección',
         'propietario': 'Propietario',
         'email': 'Correo electrónico',
         'telefono': 'Teléfono',
         'fecharegistro': 'Fecha de registro',
         'actividad': 'Actividad económica',
         'regimen': 'Regimen Tributario',
         'naturaleza': 'Naturaleza juridica',
         'stiker': 'Stiker #',
         'ica': 'Inscrito ICA',
         'observaciones': 'Observaciones',
         'fotos': 'Imagen del lugar',
     }
Esempio n. 23
0
    def __init__(self, *args, **kwargs):
        super(IPSECSettingsForm, self).__init__(*args, **kwargs)
        self = bootstrap_tooltips(self)

        KEYEXCHANGE = (
            ('ikev2', 'IKE version 2'),
        )
        DPD = (
            ('none', 'None'),
            ('clear', 'Clear'),
            ('hold', 'Hold'),
            ('restart', 'Restart'),
        )
        AUTHBY = (
            ('secret', 'PSK Authentication'),
        )

        self.fields['ipsec_keyexchange'] = ChoiceField(choices=KEYEXCHANGE, required=True, widget=Select(attrs={'class': 'form-control'}))
        self.fields['ipsec_dpdaction'] = ChoiceField(choices=DPD, required=True, widget=Select(attrs={'class': 'form-control'}))
        self.fields['ipsec_authby'] = ChoiceField(choices=AUTHBY, required=True, widget=Select(attrs={'class': 'form-control'}))
Esempio n. 24
0
 def __init__(self, attrs=None):
     widgets = (Select(attrs=attrs, choices=phone_prefixes), TextInput())
     # pylint: disable=bad-super-call
     super(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)
Esempio n. 25
0
    class Meta:
        model = Grid

        fields = (
            'message',
            'width',
            'width_unit',
            'height',
            'height_unit',
            'margin_left',
            'margin_left_unit',
            'margin_right',
            'margin_right_unit',
            'margin_top',
            'margin_top_unit',
            'margin_bottom',
            'margin_bottom_unit',
            'columns',
            'columns_color',
            'columns_opacity',
            'columns_gutter',
            'columns_gutter_unit',
            'baseline',
            'baseline_unit',
            'baseline_color',
            'baseline_opacity',
        )

        widgets = {
            'width':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'width_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
            'height':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'height_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
            'margin_left':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'margin_left_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
            'margin_right':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'margin_right_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
            'margin_top':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'margin_top_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
            'margin_bottom':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'margin_bottom_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
            'columns_color':
            TextInput(attrs={'class': 'value form-control input-sm'}),
            'columns_opacity':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'baseline_color':
            TextInput(attrs={'class': 'value form-control input-sm'}),
            'baseline_opacity':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'columns_gutter':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'columns_gutter_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
            'columns':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'baseline':
            NumberInput(attrs={'class': 'value form-control input-sm'}),
            'baseline_unit':
            Select(attrs={'class': 'units form-control input-sm'}),
        }
Esempio n. 26
0
class EpisodeForm(BetterModelForm):
    title = CharField(
        label='Title',
        widget=TextInput(attrs={
            'class': 'input',
            'type': 'text',
            'placeholder': 'Episode Title'
        }))

    subtitle = CharField(
        label='Subtitle',
        required=False,
        widget=TextInput(attrs={
            'class': 'input',
            'type': 'text',
            'placeholder': 'Episode Subtitle'
        }))

    number = CharField(label='Episode Number',
                       required=False,
                       widget=TextInput(attrs={
                           'class': 'input',
                           'type': 'text'
                       }))

    guid = CharField(label='GUID',
                     widget=TextInput(attrs={
                         'class': 'input',
                         'type': 'text'
                     }))

    description = CharField(
        label='Episode Description',
        required=False,
        widget=MarkdownWidget(attrs={
            'class': 'input textarea',
            'type': 'text',
            'rows': 6
        }))

    buffer_image = FileField(label='Episode Image',
                             required=False,
                             widget=FileInput(attrs={
                                 'class': 'input',
                                 'type': 'file'
                             }))

    pub_date = DateTimeField(label='Publication Date',
                             initial=datetime.datetime.today,
                             widget=TextInput(attrs={
                                 'class': 'input datetimepicker',
                                 'type': 'text'
                             }))
    tags = CharField(label='Tags',
                     required=False,
                     widget=TextInput(attrs={
                         'class': 'input',
                         'type': 'text'
                     }))

    active = ChoiceField(label='Ready to Publish?',
                         widget=Select(attrs={'class': 'input inline'}),
                         choices=BOOLEAN_CHOICES,
                         initial=BOOLEAN_CHOICES[0][0],
                         help_text='Is the episode ready to go live?')

    buffer_audio = FileField(label='Episode Audio',
                             required=False,
                             widget=FileInput(attrs={
                                 'class': 'input',
                                 'type': 'file'
                             }))

    show_notes = CharField(
        label='Show Notes',
        required=False,
        widget=MarkdownWidget(attrs={
            'class': 'input textarea',
            'type': 'text',
            'rows': 8
        }),
        help_text='Notes about this episode')

    credits = CharField(label='Credits',
                        required=False,
                        widget=MarkdownWidget(attrs={
                            'class': 'input textarea',
                            'type': 'text',
                            'rows': 6
                        }),
                        help_text='Art and Music Credits')

    guests = CharField(label='Guests',
                       required=False,
                       widget=MarkdownWidget(attrs={
                           'class': 'input textarea',
                           'type': 'text',
                           'rows': 6
                       }),
                       help_text='Guests appearing in this episode')

    class Meta:
        model = Episode
        fields = [
            'title', 'subtitle', 'number', 'guid', 'description',
            'buffer_image', 'pub_date', 'tags', 'active', 'buffer_audio',
            'show_notes', 'credits', 'guests'
        ]

        exclude = ('podcast', 'size', 'length', 'part', 'mime_type')
Esempio n. 27
0
    class Meta(LRecordForm.Meta):
        model = Record
        fields = [
            'date_from', 'time_from', 'date_to', 'time_to', 'user', 'wu',
            'group', 'project', 'experiment', 'remark', 'subexp'
        ]

        labels = {
            'wu': 'WU:',
            'date_from': 'From:',
            'time_from': 'Time:',
            'date_to': 'To:',
            'time_to': 'Time:',
            'experiment': 'Experiment:',
            'subexp': 'Usage',
        }

        help_texts = {
            'date_from': 'The starting date of your run',
            'date_to': 'The last date of your run',
            'time_from': 'The first session of your run',
            'time_to': 'The last session of your run',
            'experiment': 'Pick an experiment'
        }

        widgets = {
            'date_from':
            DateInput(attrs={
                'type': 'date',
                'class': 'datepicker dfrom time'
            }),
            'date_to':
            DateInput(attrs={
                'type': 'date',
                'class': 'datepicker dto time'
            }),
            'time_to':
            Select(attrs={'class': 'tto time'}),
            'time_from':
            Select(attrs={'class': 'tfrom time'}),
            'remark':
            Textarea(
                attrs={
                    'placeholder':
                    'Enter some detail here about your experiment',
                    'rows': '1',
                    'cols': '50'
                }),
            'experiment':
            Select(attrs={
                'class': 'experiment',
            }),
            'subexp':
            Select(attrs={'class': 'subexpclass'}),
            'group':
            Select(attrs={
                'class': 'group',
            }),
            'project':
            Select(attrs={
                'class': 'project',
            }),
            'user':
            Select(attrs={
                'placeholder': 'Surname Name',
                'class': 'user'
            }),
            'wu':
            NumberInput(
                attrs={
                    'required': False,
                    'class': 'uo',
                    'value': 0,
                    'min': 0,
                    'step': 0.5,
                    'style': 'width:10ch'
                }),
        }
class ConceptFilter(django_filters.FilterSet):
    registration_date = django_filters.DateFilter(
        widget=BootstrapDateTimePicker, method='noop')

    status = django_filters.ChoiceFilter(
        choices=MDR.STATES,
        method='noop',
        widget=Select(attrs={'class': 'form-control'}))

    letters = [(i, i) for i in string.ascii_uppercase + "&"]
    letter = django_filters.ChoiceFilter(
        choices=letters,
        method='noop',
        widget=Select(attrs={'class': 'form-control'}))

    class Meta:
        model = MDR._concept
        # Exclude unused fields, otherwise they appear in the template
        fields: list = []

    def __init__(self, *args, **kwargs):
        # Override the init method so we can pass the iid to the queryset
        self.registration_authority_id = kwargs.pop(
            'registration_authority_id')

        # This is overridden because otherwise it runs on docs CI
        self.base_filters[
            'concept_type'] = django_filters.MultipleChoiceFilter(
                choices=get_concept_type_choices(),
                method='noop',
                widget=ModelSelect2Multiple)

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

        self.queryset = self.queryset.visible(self.request.user)

    def noop(self, queryset, name, value):
        return queryset

    @property
    def qs(self):
        # We're doing all the filtering at once here in order to improve filtering performance
        from django.db.models.functions import Upper, Substr
        from django.db.models import Q, Subquery

        if not self.form.is_valid():
            return super().qs

        if not hasattr(self, '_qs'):
            qs = super().qs
            selected_date = self.form.cleaned_data['registration_date']
            selected_state = self.form.cleaned_data['status']
            selected_letter = self.form.cleaned_data['letter']

            selected_types = self.form.cleaned_data['concept_type']

            # If they haven't selected anything
            if selected_state == '':
                selected_state = None

            if not selected_types:
                selected_types = None

            # Return all the statuses that are valid at a particular date and then
            # filter on the concepts linked to a valid status.
            # Return only the statuses that are linked to the RA for the page that you are on
            status_is_valid = Q(statuses__in=Subquery(
                MDR.Status.objects.filter(
                    state=selected_state,
                    registrationAuthority__id=self.registration_authority_id).
                valid_at_date(when=selected_date).values('pk')))

            inner = MDR._concept.objects.filter(status_is_valid)
            qs = qs.filter(pk__in=Subquery(inner.values(
                'pk'))).prefetch_related('statuses__registrationAuthority')

            # Filter on the selected concept types
            if selected_types is not None:
                qs = qs.filter(_type__in=selected_types)

            qs = qs.annotate(first_letter=Upper(Substr('name', 1, 1)))
            if selected_letter == "&":
                qs = qs.filter(~Q(first_letter__in=string.ascii_uppercase))
            elif selected_letter in string.ascii_uppercase:
                qs = qs.filter(name__istartswith=selected_letter)

            self._qs = qs.order_by(Upper('name'))

        return self._qs
Esempio n. 29
0
 class Meta:
     model = Task
     fields = [
         'name',
         'text',
         'assigned_to',
         'status',
         'important',
         'due_date',
         'project',
         'series',
         'story',
         'event',
     ]
     widgets = {
         'name':
         Textarea(attrs={
             'class': 'form-control',
             'rows': 2,
             'placeholder': 'Name'
         }),
         'text':
         Textarea(
             attrs={
                 'class': 'form-control',
                 'id': 'task-text',
                 'rows': 17,
                 'placeholder': 'Details'
             }),
         'assigned_to':
         ArrayFieldSelectMultiple(
             attrs={
                 'class': 'chosen-select form-control task-assign-select',
                 'id': 'task-team',
                 'data-placeholder': 'Assign to'
             }),
         'status':
         Select(attrs={
             'class': 'custom-select',
             'id': 'task-status'
         }),
         'important':
         CheckboxInput(attrs={'class': ''}),
         'project':
         Select(attrs={
             'class': 'custom-select',
             'id': 'task-projects'
         }),
         'series':
         Select(attrs={
             'class': 'custom-select',
             'id': 'task-series'
         }),
         'story':
         Select(attrs={
             'class': 'custom-select',
             'id': 'task-stories'
         }),
         'event':
         Select(attrs={
             'class': 'custom-select',
             'id': 'task-events'
         }),
     }
Esempio n. 30
0
class BylawForm(ModelForm):
    raspr_date = DateField(required=False,
                           widget=DateInput(attrs={'type': "text", 'class': "form-control col-6", 'id': "raspr_date"}))

    district = ModelChoiceField(required=False, queryset=DistrictsMenu.objects.all(), to_field_name="district",
                                widget=Select(attrs={'id': "district", 'class': 'form-control col-6'}))

    department = ModelChoiceField(required=False, queryset=DepartmentsMenu.objects.all(), to_field_name="department",
                                  widget=Select(attrs={'id':"department", 'class': "form-control col-6"}))

    organization = CharField(required=False, widget=TextInput(
                attrs={'type': "text", 'class': "form-control col-6 org", 'id': "organization"}))

    inn = CharField(required=True, widget=TextInput(
                attrs={'type': "text", 'class': "form-control col-6", 'id': "inn"}))

    performer = ModelChoiceField(required=False, queryset=PerformersMenu.objects.all(), to_field_name="performer",
                                 widget=Select(attrs={'id': "performer", 'class': 'form-control col-6'}))

    check_type = ModelChoiceField(required=False, queryset=CheckTypesMenu.objects.all(), to_field_name="check_type",
                                  widget=Select(attrs={'id': "check_type", 'class': 'form-control col-6'}))

    date_proved_c = DateField(required=False,
                        widget=DateInput(attrs={'type': "text", 'class': "form-control col-6", 'id': "date_proved_c"}))

    date_proved_po = DateField(required=False,
                        widget=DateInput(attrs={'type': "text", 'class': "form-control col-6", 'id': "date_proved_po"}))

    base = ModelChoiceField(required=False, queryset=BaseMenu.objects.all(), to_field_name="base",
                                  widget=Select(attrs={'id': "base", 'class': 'form-control col-6'}))

    lab_security = ModelChoiceField(required=False, queryset=LabSecurityMenu.objects.all(), to_field_name="lab_security",
                                  widget=Select(attrs={'id': "lab_security", 'class': 'form-control col-6'}))




    class Meta:
        model = BylawModel
        fields = ['raspr_date', 'district', 'department', 'organization', 'inn',
                  'performer', 'check_type', 'date_proved_c', 'date_proved_po',
                  'base', 'lab_security', 'raspr_num', 'who_created'
        ]
        widgets = {
            # 'raspr_date': DateInput(
            #     attrs={'type': "text", 'class': "form-control col-6", 'id':"raspr_date", 'required':"false"}
            # ),
            # 'organization': TextInput(
            #     attrs={'type': "text", 'class': "form-control col-6 org", 'id': "organization", 'required':"false"}
            # ),
            # 'inn': TextInput(
            #     attrs={'type': "text", 'required':"gfggfgfgfg", 'class': "form-control col-6", 'id': "inn"}
            # ),
            # 'date_proved': DateInput(
            #     attrs={'type': "text", 'class': "form-control col-6", 'id': "date_proved", 'required':"false"}
            # ),
            'raspr_num': TextInput(
                attrs={'type': "text", 'class': "form-control col-10", 'id': "raspr_num", 'readonly': ''}
            ),
            'who_created': TextInput(
                attrs={'type': "text", 'class': "form-control col-10", 'id': "who_created", 'readonly': ''}
            )
        }
Esempio n. 31
0
 def __init__(self, nfields=5, choices=(), attrs=None):
     self.nfields = nfields
     widgets = [
         Select(choices=choices, attrs=attrs) for i in range(self.nfields)
     ]
     super(MultiSelect, self).__init__(widgets, attrs)