Esempio n. 1
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['date'] = forms.DateField(widget=forms.DateInput(
         format='%Y-%m-%d', attrs={'type': 'date'}), )
Esempio n. 2
0
class EventFilterForm(forms.Form):

    category = forms.ModelChoiceField(
        label='Категория',
        queryset=Category.objects.all(),
        required=False,
    )
    features = forms.ModelMultipleChoiceField(
        label='Свойства',
        queryset=Feature.objects.all(),
        required=False,
    )
    date_start = forms.DateTimeField(label='Дата начала',
                                     widget=forms.DateInput(
                                         format="%Y-%m-%d",
                                         attrs={'type': 'date'}),
                                     required=False)
    date_end = forms.DateTimeField(label='Дата конца',
                                   widget=forms.DateInput(
                                       format="%Y-%m-%d",
                                       attrs={'type': 'date'}),
                                   required=False)
    is_private = forms.BooleanField(
        label='Приватное',
        widget=forms.CheckboxInput(attrs={'type': 'checkbox'}),
        required=False)
    is_available = forms.BooleanField(
        label='Есть места',
        widget=forms.CheckboxInput(attrs={'type': 'checkbox'}),
        required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs.update({'class': 'special'})

        self.fields['category'].widget.attrs.update({
            'class':
            'form-control',
            'selected':
            "selected",
            'initial':
            self.fields['category']
        })
        self.fields['features'].widget.attrs.update({
            'class':
            'form-control',
            'multiple':
            True,
            'selected':
            "selected",
            'initial':
            self.fields['features']
        })
        self.fields['date_start'].widget.attrs.update(
            {'class': 'form-control mx-1'})
        self.fields['date_end'].widget.attrs.update(
            {'class': 'form-control mx-1'})
        self.fields['is_private'].widget.attrs.update({
            'class': 'form-check',
            'default': False
        })
        self.fields['is_available'].widget.attrs.update({
            'class': 'form-check ',
            'default': False
        })
Esempio n. 3
0
class ExperimentOverviewForm(UniqueNameSlugFormMixin, ChangeLogMixin,
                             forms.ModelForm):

    type = forms.ChoiceField(
        label="Type",
        choices=Experiment.TYPE_CHOICES,
        help_text=Experiment.TYPE_HELP_TEXT,
    )
    owner = forms.ModelChoiceField(
        required=True,
        label="Experiment Owner",
        help_text=Experiment.OWNER_HELP_TEXT,
        queryset=get_user_model().objects.all().order_by("email"),
        # This one forces the <select> widget to not include a blank
        # option which would otherwise be included because the model field
        # is nullable.
        empty_label=None,
    )
    engineering_owner = forms.CharField(
        required=False,
        label="Engineering Owner",
        help_text=Experiment.ENGINEERING_OWNER_HELP_TEXT,
    )
    name = forms.CharField(label="Name", help_text=Experiment.NAME_HELP_TEXT)
    slug = forms.CharField(required=False, widget=forms.HiddenInput())
    short_description = forms.CharField(
        label="Short Description",
        help_text=Experiment.SHORT_DESCRIPTION_HELP_TEXT,
        widget=forms.Textarea(attrs={"rows": 3}),
    )
    data_science_bugzilla_url = BugzillaURLField(
        label="Data Science Bugzilla URL",
        help_text=Experiment.DATA_SCIENCE_BUGZILLA_HELP_TEXT,
    )
    feature_bugzilla_url = BugzillaURLField(
        required=False,
        label="Feature Bugzilla URL",
        help_text=Experiment.FEATURE_BUGZILLA_HELP_TEXT,
    )
    related_work = forms.CharField(
        required=False,
        label="Related Work URLs",
        help_text=Experiment.RELATED_WORK_HELP_TEXT,
        widget=forms.Textarea(attrs={"rows": 3}),
    )
    proposed_start_date = forms.DateField(
        required=False,
        label="Proposed Start Date",
        help_text=Experiment.PROPOSED_START_DATE_HELP_TEXT,
        widget=forms.DateInput(attrs={
            "type": "date",
            "class": "form-control"
        }),
    )
    proposed_duration = forms.IntegerField(
        required=False,
        min_value=1,
        label="Proposed Experiment Duration (days)",
        help_text=Experiment.PROPOSED_DURATION_HELP_TEXT,
        widget=forms.NumberInput(attrs={"class": "form-control"}),
    )
    proposed_enrollment = forms.IntegerField(
        required=False,
        min_value=1,
        label="Proposed Enrollment Duration (days)",
        help_text=Experiment.PROPOSED_ENROLLMENT_HELP_TEXT,
        widget=forms.NumberInput(attrs={"class": "form-control"}),
    )

    class Meta:
        model = Experiment
        fields = [
            "type",
            "owner",
            "engineering_owner",
            "name",
            "slug",
            "short_description",
            "data_science_bugzilla_url",
            "feature_bugzilla_url",
            "related_work",
            "proposed_start_date",
            "proposed_duration",
            "proposed_enrollment",
        ]

    def clean_proposed_start_date(self):
        start_date = self.cleaned_data["proposed_start_date"]

        if start_date and start_date < timezone.now().date():
            raise forms.ValidationError(
                ("The experiment start date must "
                 "be no earlier than the current date."))

        return start_date

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

        # enrollment may be None
        enrollment = cleaned_data.get("proposed_enrollment", None)
        duration = cleaned_data.get("proposed_duration", None)

        if (enrollment and duration) and enrollment > duration:
            msg = ("The enrollment duration must be less than "
                   "or equal to the experiment duration.")
            self._errors["proposed_enrollment"] = [msg]

        return cleaned_data
Esempio n. 4
0
class ControllersForm(forms.ModelForm):
    controller_name = forms.CharField(
        max_length=25,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Controller Name"
        }))
    controllerid = forms.CharField(
        max_length=15,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Controller ID"
        }))
    ipaddress = forms.CharField(
        max_length=15,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "IP Address"
        }))
    serial_number = forms.CharField(
        max_length=15,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Serial Number"
        }))
    name = forms.CharField(max_length=15,
                           required=False,
                           widget=forms.TextInput(attrs={
                               "class": "form-control",
                               'placeholder': "Name"
                           }))
    doorcurrentstatus = forms.CharField(
        max_length=15,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Door Current Status"
        }))
    doorlastopeneddate = forms.DateField(
        required=False,
        widget=forms.DateInput(
            attrs={
                "class": "form-control datepicker",
                'placeholder': "Door last oppened date"
            }))
    doorlastopenedtime = forms.TimeField(
        required=False,
        widget=forms.TextInput(
            attrs={
                "class": "form-control timepicker",
                'placeholder': "Door last oppened time"
            }))
    doorlastcloseddate = forms.DateField(
        required=False,
        widget=forms.DateInput(
            attrs={
                "class": "form-control datepicker",
                'placeholder': "Door last closed date"
            }))
    doorlastclosedtime = forms.TimeField(
        required=False,
        widget=forms.TextInput(
            attrs={
                "class": "form-control timepicker",
                'placeholder': "Door last closed time"
            }))

    card_1_name = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Card 1 name"
        }))
    card_1_type = forms.ChoiceField(
        choices=alarm_input_choices,
        widget=forms.Select(attrs={"class": "form-control"}))
    card_1_lastdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "Card 1 last date"
        }))
    card_1_lasttime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "Card 1 last time"
        }))
    card_1_lastuser = forms.CharField(
        max_length=30,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Card 1 last user"
        }))
    card_1_lastcard = forms.CharField(
        max_length=15,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Card 1 last card"
        }))

    card_2_name = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Card 2 name"
        }))
    card_2_type = forms.ChoiceField(
        choices=alarm_input_choices,
        widget=forms.Select(attrs={"class": "form-control"}))
    card_2_lastdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "Card 2 last date"
        }))
    card_2_lasttime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "Card 2 last time"
        }))
    card_2_lastuser = forms.CharField(
        max_length=30,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Card 2 last user"
        }))
    card_2_lastcard = forms.CharField(
        max_length=15,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Card 2 last card"
        }))

    input_1_name = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 1 name"
        }))
    input_1_type = forms.ChoiceField(
        choices=alarm_input_choices,
        widget=forms.Select(attrs={"class": "form-control"}))
    input_1_status = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 1 status"
        }))
    input_1_lastdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "Input 1 last date"
        }))
    input_1_lasttime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "Input 1 last time"
        }))
    input_1_laststate = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 1 laststate"
        }))

    input_2_name = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 2 name"
        }))
    input_2_type = forms.ChoiceField(
        choices=alarm_input_choices,
        widget=forms.Select(attrs={"class": "form-control"}))
    input_2_status = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 2 status"
        }))
    input_2_lastdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "Input 2 last date"
        }))
    input_2_lasttime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "Input 2 last time"
        }))
    input_2_laststate = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 2 laststate"
        }))

    input_3_name = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 3 name"
        }))
    input_3_type = forms.ChoiceField(
        choices=alarm_input_choices,
        widget=forms.Select(attrs={"class": "form-control"}))
    input_3_status = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 3 status"
        }))
    input_3_lastdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "Input 3 last date"
        }))
    input_3_lasttime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "Input 3 last time"
        }))
    input_3_laststate = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 3 laststate"
        }))

    input_4_name = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 4 name"
        }))
    input_4_type = forms.ChoiceField(
        choices=alarm_input_choices,
        widget=forms.Select(attrs={"class": "form-control"}))
    input_4_status = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 4 status"
        }))
    input_4_lastdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "Input 4 last date"
        }))
    input_4_lasttime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "Input 4 last time"
        }))
    input_4_laststate = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Input 4 laststate"
        }))

    controller_alarm_laststate = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': 'Controller Alarm Last State'
        }))
    controller_alarm_lastdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "Date Last Tripped"
        }))
    controller_alarm_lasttime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "Time Last Tripped"
        }))

    class Meta:
        model = Controllers
        exclude = ['search_string']

    def save(self, commit=True):
        controller = super(ControllersForm, self).save(commit=False)
        controller.search_string = controller.controller_name + " " + controller.card_1_name + " " + controller.card_1_type + " " + controller.card_2_name + " " + controller.card_2_type + " " + controller.input_1_name + " " + controller.input_1_type + " " + controller.input_2_name + " " + controller.input_2_type + " " + controller.input_3_name + " " + controller.input_3_type + " " + controller.input_3_name + " " + controller.input_4_type + " " + controller.input_4_name
        controller.save()
        return controller
Esempio n. 5
0
 class Meta:
     model = Task
     fields = ('title', 'date', 'body')
     widgets = {
     'date': forms.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'placeholder':'Select a date', 'type':'date'}),
     }
Esempio n. 6
0
FIELD_IS_ACTIVE = forms.BooleanField(
    label=_('ADMINISTRATION_MODULE_SECURITY_IMPORTEDLDAPUSER_IS_ACTIVE'),
    required=False,
    widget=forms.CheckboxInput(attrs={
        'id': 'is_active',
        'aria-describedby': 'is_active_icon',
        'icon': 'fa fa-check-square-o',
    }, ),
)
FIELD_CREATED = forms.DateField(
    label=_('ADMINISTRATION_MODULE_SECURITY_IMPORTEDLDAPUSER_CREATED'),
    required=False,
    widget=forms.DateInput(attrs={
        'id': 'created',
        'aria-describedby': 'created_icon',
        'icon': 'fa fa-clock-o',
    }, ),
)
FIELD_MODIFIED = forms.DateField(
    label=_('ADMINISTRATION_MODULE_SECURITY_IMPORTEDLDAPUSER_MODIFIED'),
    required=False,
    widget=forms.DateInput(attrs={
        'id': 'modified',
        'aria-describedby': 'modified_icon',
        'icon': 'fa fa-clock-o',
    }, ),
)
FIELD_AVATAR = forms.ImageField(
    label=_('ADMINISTRATION_MODULE_SECURITY_IMPORTEDLDAPUSER_AVATAR'),
    required=False,
Esempio n. 7
0
class DashboardFeedFilterForm(forms.Form):
    """
    A form used to configure the filters on a Dashboard Feed export
    """
    emwf_case_filter = forms.Field(
        label=ugettext_lazy("Case Owner(s)"),
        required=False,
        widget=Select2Ajax(multiple=True),
        help_text=ExpandedMobileWorkerFilter.location_search_help,
    )
    emwf_form_filter = forms.Field(
        label=ugettext_lazy("User(s)"),
        required=False,
        widget=Select2Ajax(multiple=True),
        help_text=ExpandedMobileWorkerFilter.location_search_help,
    )
    date_range = forms.ChoiceField(
        label=ugettext_lazy("Date Range"),
        required=True,
        initial="last7",
        choices=[
            ("last7", ugettext_lazy("Last 7 days")),
            ("last30", ugettext_lazy("Last 30 days")),
            ("lastmonth", ugettext_lazy("Last month")),
            ("lastyear", ugettext_lazy("Last year")),
            ("lastn", ugettext_lazy("Days ago")),
            ("since", ugettext_lazy("Since a date")),
            ("range", ugettext_lazy("From a date to a date")),
        ],
        help_text='''
            <span data-bind='visible: showEmwfFormFilter'>{}</span>
            <span data-bind='visible: showEmwfCaseFilter'>{}</span>
        '''.format(
            ugettext_lazy("Export forms received in this date range."),
            ugettext_lazy("Export cases modified in this date range."),
        ))
    days = forms.IntegerField(
        label=ugettext_lazy("Number of Days"),
        required=False,
    )
    start_date = forms.DateField(
        label=ugettext_lazy("Begin Date"),
        required=False,
        widget=forms.DateInput(format="%Y-%m-%d",
                               attrs={"placeholder": "YYYY-MM-DD"}),
        help_text="<small class='label label-default'>{}</small>".format(
            ugettext_lazy("YYYY-MM-DD")),
    )
    end_date = forms.DateField(
        label=ugettext_lazy("End Date"),
        required=False,
        widget=forms.DateInput(format="%Y-%m-%d",
                               attrs={"placeholder": "YYYY-MM-DD"}),
        help_text="<small class='label label-default'>{}</small>".format(
            ugettext_lazy("YYYY-MM-DD")),
    )
    update_location_restriction = forms.BooleanField(
        label=ugettext_lazy("Update location restriction to match filters."),
        required=False,
    )

    def __init__(self, domain_object, *args, **kwargs):
        self.domain_object = domain_object
        self.can_user_access_all_locations = True
        if 'couch_user' in kwargs:
            couch_user = kwargs.pop('couch_user')
            self.can_user_access_all_locations = couch_user.has_permission(
                domain_object.name, 'access_all_locations')
        super(DashboardFeedFilterForm, self).__init__(*args, **kwargs)

        self.can_restrict_access_by_location = domain_object.has_privilege(
            privileges.RESTRICT_ACCESS_BY_LOCATION)

        if not self.can_restrict_access_by_location or not self.can_user_access_all_locations:
            del self.fields['update_location_restriction']

        self.fields['emwf_case_filter'].widget.set_url(
            reverse(CaseListFilter.options_url,
                    args=(self.domain_object.name, )))
        self.fields['emwf_form_filter'].widget.set_url(
            reverse(ExpandedMobileWorkerFilter.options_url,
                    args=(self.domain_object.name, )))

        self.helper = HQModalFormHelper()
        self.helper.form_tag = False
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-10 col-lg-10'
        self.helper.layout = crispy.Layout(*self.layout_fields)

    def clean(self):
        cleaned_data = super(DashboardFeedFilterForm, self).clean()
        errors = []

        if cleaned_data['emwf_form_filter'] and cleaned_data[
                'emwf_case_filter']:
            # This should only happen if a user builds the reqest manually or there is an error rendering the form
            forms.ValidationError(
                _("Cannot submit case and form users and groups filter"))

        date_range = cleaned_data['date_range']
        if date_range in ("since", "range") and not cleaned_data.get(
                'start_date', None):
            errors.append(
                forms.ValidationError(_("A valid start date is required")))
        if date_range == "range" and not cleaned_data.get('end_date', None):
            errors.append(
                forms.ValidationError(_("A valid end date is required")))
        if errors:
            raise forms.ValidationError(errors)

    def format_export_data(self, export):
        return {
            'domain': self.domain_object.name,
            'sheet_name': export.name,
            'export_id': export.get_id,
            'export_type': self._export_type,
            'name': export.name,
            'edit_url': self.get_edit_url(export),
        }

    @property
    def layout_fields(self):
        fields = [
            crispy.Div(
                crispy.Field('emwf_case_filter', ),
                data_bind="visible: showEmwfCaseFilter",
            ),
            crispy.Div(
                crispy.Field('emwf_form_filter', ),
                data_bind="visible: showEmwfFormFilter",
            ),
            crispy.Field(
                'date_range',
                data_bind='value: dateRange',
            ),
            crispy.Div(
                crispy.Field("days", data_bind="value: days"),
                data_bind="visible: showDays",
            ),
            crispy.Div(
                crispy.Field(
                    "start_date",
                    data_bind="value: startDate",
                ),
                data_bind=
                "visible: showStartDate, css: {'has-error': startDateHasError}",
            ),
            crispy.Div(
                crispy.Field(
                    "end_date",
                    data_bind="value: endDate",
                ),
                data_bind=
                "visible: showEndDate, css: {'has-error': endDateHasError}",
            ),
        ]
        if self.can_restrict_access_by_location and self.can_user_access_all_locations:
            fields.append(
                crispy.Fieldset(
                    _("Location Management"),
                    crispy.Field(
                        'update_location_restriction',
                        data_bind='checked: updateLocationRestriction',
                    ),
                ))
        return fields

    def to_export_instance_filters(self, can_access_all_locations,
                                   accessible_location_ids, export_type):
        """
        Serialize the bound form as an ExportInstanceFilters object.
        """
        # Confirm that either form filter data or case filter data but not both has been submitted.
        assert ((self.cleaned_data['emwf_form_filter'] is not None) !=
                (self.cleaned_data['emwf_case_filter'] is not None))
        assert (export_type == 'form' or export_type == 'case')
        if export_type == 'form':
            filters = self._to_form_export_instance_filters(
                can_access_all_locations, accessible_location_ids)
        else:
            filters = self._to_case_export_instance_filters(
                can_access_all_locations, accessible_location_ids)

        if (self.can_user_access_all_locations
                and self.can_restrict_access_by_location
                and self.cleaned_data['update_location_restriction']):
            filters.accessible_location_ids = filters.locations
            filters.can_access_all_locations = not filters.locations
        return filters

    def _to_case_export_instance_filters(self, can_access_all_locations,
                                         accessible_location_ids):
        emwf_selections = self.cleaned_data["emwf_case_filter"]

        return CaseExportInstanceFilters(
            date_period=DatePeriod(
                period_type=self.cleaned_data['date_range'],
                days=self.cleaned_data['days'],
                begin=self.cleaned_data['start_date'],
                end=self.cleaned_data['end_date'],
            ),
            users=CaseListFilter.selected_user_ids(emwf_selections),
            reporting_groups=CaseListFilter.selected_reporting_group_ids(
                emwf_selections),
            locations=CaseListFilter.selected_location_ids(emwf_selections),
            user_types=CaseListFilter.selected_user_types(emwf_selections),
            can_access_all_locations=can_access_all_locations,
            accessible_location_ids=accessible_location_ids,
            sharing_groups=CaseListFilter.selected_sharing_group_ids(
                emwf_selections),
            show_all_data=CaseListFilter.show_all_data(emwf_selections)
            or CaseListFilter.no_filters_selected(emwf_selections),
            show_project_data=CaseListFilter.show_project_data(
                emwf_selections),
        )

    def _to_form_export_instance_filters(self, can_access_all_locations,
                                         accessible_location_ids):
        emwf_selections = self.cleaned_data["emwf_form_filter"]

        return FormExportInstanceFilters(
            date_period=DatePeriod(
                period_type=self.cleaned_data['date_range'],
                days=self.cleaned_data['days'],
                begin=self.cleaned_data['start_date'],
                end=self.cleaned_data['end_date'],
            ),
            users=ExpandedMobileWorkerFilter.selected_user_ids(
                emwf_selections),
            reporting_groups=ExpandedMobileWorkerFilter.
            selected_reporting_group_ids(emwf_selections),
            locations=ExpandedMobileWorkerFilter.selected_location_ids(
                emwf_selections),
            user_types=ExpandedMobileWorkerFilter.selected_user_types(
                emwf_selections),
            can_access_all_locations=can_access_all_locations,
            accessible_location_ids=accessible_location_ids,
        )

    @classmethod
    def get_form_data_from_export_instance_filters(cls,
                                                   export_instance_filters,
                                                   domain, export_type):
        """
        Return a dictionary representing the form data from a given ExportInstanceFilters.
        This is used to populate a form from an existing export instance
        :param export_instance_filters:
        :return:
        """
        if export_instance_filters:
            date_period = export_instance_filters.date_period
            selected_items = (export_instance_filters.users +
                              export_instance_filters.reporting_groups +
                              export_instance_filters.locations +
                              export_instance_filters.user_types)
            if isinstance(export_instance_filters, CaseExportInstanceFilters):
                selected_items += (
                    export_instance_filters.sharing_groups +
                    (["all_data"] if export_instance_filters.show_all_data else
                     []) + (["project_data"] if
                            export_instance_filters.show_project_data else []))

            emwf_utils_class = CaseListFilterUtils if export_type is CaseExportInstance else \
                EmwfUtils
            emwf_data = []
            for item in selected_items:
                choice_tuple = emwf_utils_class(domain).id_to_choice_tuple(
                    str(item))
                if choice_tuple:
                    emwf_data.append({
                        "id": choice_tuple[0],
                        "text": choice_tuple[1]
                    })

            return {
                "date_range": date_period.period_type if date_period else None,
                "days": date_period.days if date_period else None,
                "start_date": date_period.begin if date_period else None,
                "end_date": date_period.end if date_period else None,
                "emwf_form_filter": emwf_data,
                "emwf_case_filter": emwf_data,
            }
        else:
            return None
Esempio n. 8
0
class NewSingleSlotForm(forms.Form):
    title = forms.CharField(label='Title',
                            max_length=30,
                            required=True,
                            widget=forms.TextInput(attrs={
                                'type': 'text',
                                'class': 'form-control'
                            }))
    description = forms.CharField(
        label='Description',
        required=False,
        widget=forms.TextInput(attrs={
            'type': 'text',
            'class': 'form-control'
        }))
    start = forms.DateTimeField(
        label='Start time',
        required=True,
        input_formats=['%Y-%m-%dT%H:%M'],
        widget=forms.DateTimeInput(attrs={
            'type': 'datetime-local',
            'class': 'form-control'
        }))
    end = forms.DateTimeField(
        label='End time',
        required=True,
        input_formats=['%Y-%m-%dT%H:%M'],
        widget=forms.DateTimeInput(attrs={
            'type': 'datetime-local',
            'class': 'form-control'
        }))

    location = forms.CharField(label='Location',
                               required=False,
                               max_length=240,
                               widget=forms.TextInput(attrs={
                                   'type': 'text',
                                   'class': 'form-control'
                               }))
    address = forms.CharField(label='Address',
                              required=False,
                              max_length=240,
                              widget=forms.TextInput(attrs={
                                  'type': 'text',
                                  'class': 'form-control'
                              }))
    city = forms.CharField(label='City',
                           required=False,
                           max_length=240,
                           widget=forms.TextInput(attrs={
                               'type': 'text',
                               'class': 'form-control'
                           }))
    state = forms.CharField(label='State',
                            required=False,
                            max_length=2,
                            widget=forms.TextInput(attrs={
                                'type': 'text',
                                'class': 'form-control'
                            }))
    zip_code = forms.IntegerField(
        label='Zip Code',
        required=False,
        widget=forms.NumberInput(attrs={
            'type': 'number',
            'max': '99999',
            'class': 'form-control'
        }))

    maxVolunteers = forms.IntegerField(
        label='# of Slots',
        required=False,
        widget=forms.NumberInput(attrs={
            'type': 'number',
            'min': '1',
            'class': 'form-control'
        }))

    in_person = forms.BooleanField(
        label='In person',
        required=False,
        widget=forms.CheckboxInput(attrs={
            'type': 'checkbox',
            'class': 'form-control'
        }))

    TESTdateField = {
        'DateField': forms.DateInput(attrs={'id': 'datetimepicker12'})
    }

    user = models.User()
    datetime = get_dt()

    extraFields = forms.CharField(
        label='Extra Fields (Seperate w/ Commas)',
        required=False,
        max_length=240,
        widget=forms.TextInput(attrs={
            'type': 'text',
            'class': 'form-control'
        }))

    private = forms.BooleanField(label='Private', required=False)

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

    def clean_title(self):
        title = self.cleaned_data['title']
        return title

    def clean_description(self):
        description = self.cleaned_data['description']
        return description

    def clean_location(self):
        user = self.cleaned_data['location']
        return user

    def clean_address(self):
        user = self.cleaned_data['address']
        return user

    def clean_city(self):
        user = self.cleaned_data['city']
        return user

    def clean_state(self):
        user = self.cleaned_data['state']
        return user

    def clean_zip_code(self):
        user = self.cleaned_data['zip_code']
        return user

    def clean_maxVolunteers(self):
        description = self.cleaned_data['maxVolunteers']
        return description

    def clean_in_person(self):
        in_person = self.cleaned_data['in_person']
        return in_person

    def clean_user(self):
        user = self.cleaned_data['user']
        return user

    def clean_start(self):
        start = self.cleaned_data['start']
        return start

    def clean_end(self):
        end = self.cleaned_data['end']
        return end

    def clean_extra(self):
        a = self.cleaned_data['extraFields']
        print(a)
        ans = {}
        for i in a.split(','):
            ans[i] = '-'

        return ans

    def clean_private(self):
        private = self.cleaned_data['private']
        return private

    def save(self, commit=True):
        event = Event(organizer=self.user,
                      name=self.cleaned_data['title'],
                      description=self.cleaned_data['description'],
                      location=self.cleaned_data['location'],
                      address=self.cleaned_data['address'],
                      city=self.cleaned_data['city'],
                      state=self.cleaned_data['state'],
                      zip_code=self.cleaned_data['zip_code'],
                      in_person=self.cleaned_data['in_person'],
                      maxVolunteers=self.cleaned_data['maxVolunteers'],
                      extraFields=self.cleaned_data['extraFields'],
                      minVolunteers=1,
                      volunteers=None,
                      start=self.cleaned_data['start'],
                      end=self.cleaned_data['end'],
                      private=self.cleaned_data['private'],
                      is_single=True,
                      type='singleSlot')
        return event
Esempio n. 9
0
 class Meta:
     model = Event
     fields = '__all__'
     widgets = {'date': forms.DateInput(attrs={'class': 'datepicker'})}
Esempio n. 10
0
class SalesSearchForm(forms.Form):
    date_from = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
    date_to = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
    chart_type = forms.ChoiceField(choices=CHART_CHOICES)
    results_by = forms.ChoiceField(choices=RESULT_CHOICES)
Esempio n. 11
0
 class Meta:
     model = Customer
     fields = '__all__'
     wigets = {
         'date_of_birth': forms.DateInput(attrs={'placeholder': 'YYYY-MM-DD'})
     }
Esempio n. 12
0
from django import forms
from .models import General, HotWorks, ElectricalWorks

form_styles = {
    'contractor': forms.TextInput(attrs={'class': 'textinputfield'}),
    'contractor_name': forms.TextInput(attrs={'class': 'textinputfield'}),
    'facility': forms.TextInput(attrs={'class': 'textinputfield'}),
    'date_of_arrival': forms.DateInput(attrs={'class': 'textinputfield'}),
    'time_of_arrival': forms.TimeInput(attrs={'class': 'textinputfield'}),
    'date_of_finish': forms.DateInput(attrs={'class': 'textinputfield'}),
    'time_of_finish': forms.TimeInput(attrs={'class': 'textinputfield'}),
    'job_location': forms.TextInput(attrs={'class': 'textinputfield'}),
    'job_spec': forms.TextInput(attrs={'class': 'textinputfield'}),
    'equipment': forms.TextInput(attrs={'class': 'textinputfield'}),
    'safety_precautions': forms.TextInput(attrs={'class': 'textinputfield'}),
    'location1': forms.TextInput(attrs={'class': 'textinputfield'}),
    'location2': forms.TextInput(attrs={'class': 'textinputfield'}),
    'location3': forms.TextInput(attrs={'class': 'textinputfield'}),
}

field_order_list = (
    'contractor',
    'contractor_name',
    'facility',
    'date_of_arrival',
    'time_of_arrival',
    'date_of_finish',
    'time_of_finish',
    'job_location',
    'job_spec',
    'equipment',
Esempio n. 13
0
class PatientRelativeForm(forms.ModelForm):
    class Meta:
        model = PatientRelative
        fields = "__all__"  # Added after upgrading to Django 1.8
        # Added after upgrading to Django 1.8  - uniqueness check was failing
        # otherwise (RDR-1039)
        exclude = ['id']
        widgets = {
            'relative_patient': PatientRelativeLinkWidget,
        }

    date_of_birth = forms.DateField(widget=forms.DateInput(
        attrs={'class': 'datepicker'}, format='%d-%m-%Y'),
                                    help_text=_("DD-MM-YYYY"),
                                    input_formats=['%d-%m-%Y'])

    def __init__(self, *args, **kwargs):
        self.create_patient_data = None
        super(PatientRelativeForm, self).__init__(*args, **kwargs)
        self.create_patient_flag = False
        self.tag = None  # used to locate this form

    def _clean_fields(self):
        self._errors = ErrorDict()
        num_errors = 0
        if not self.is_bound:  # Stop further processing.
            return
        self.cleaned_data = {}
        # check for 'on' checkbox value for patient relative checkbox ( which means create patient )\
        # this 'on' value from widget is replaced by the pk of the created patient
        for name, field in list(self.fields.items()):
            try:
                value = field.widget.value_from_datadict(
                    self.data, self.files, self.add_prefix(name))
                if name == "relative_patient":
                    if value == "on":
                        self.cleaned_data[name] = None
                        self.create_patient_flag = True
                    else:
                        self.cleaned_data[name] = value

                elif name == 'date_of_birth':
                    try:
                        self.cleaned_data[name] = self._set_date_of_birth(
                            value)
                    except Exception:
                        raise ValidationError(
                            "Date of Birth must be dd-mm-yyyy")

                elif name == 'patient':
                    continue  # this was causing error in post clean - we set this ourselves
                else:
                    self.cleaned_data[name] = value

            except ValidationError as e:
                num_errors += 1
                self._errors[name] = self.error_class(e.messages)
                if name in self.cleaned_data:
                    del self.cleaned_data[name]

        self.tag = self.cleaned_data["given_names"] + self.cleaned_data[
            "family_name"]

    def _set_date_of_birth(self, dob):
        # todo figure  out why the correct input format is not being respected -
        # the field for dob on PatientRelative is in aus format already
        parts = dob.split("-")
        return "-".join([parts[2], parts[1], parts[0]])

    def _get_patient_relative_data(self, index):
        data = {}
        for k in self.data:
            if k.startswith("relatives-%s-" % index):
                data[k] = self.data[k]
        return data
Esempio n. 14
0
class PatientForm(forms.ModelForm):

    ADDRESS_ATTRS = {
        "rows": 3,
        "cols": 30,
    }

    next_of_kin_country = forms.ChoiceField(
        required=False,
        widget=CountryWidget(attrs={'onChange': 'select_country(this);'}))
    next_of_kin_state = forms.ChoiceField(required=False, widget=StateWidget())
    country_of_birth = forms.ChoiceField(required=False,
                                         widget=CountryWidget())

    def __init__(self, *args, **kwargs):
        clinicians = CustomUser.objects.all()
        instance = None

        if 'registry_model' in kwargs:
            self.registry_model = kwargs['registry_model']
            del kwargs['registry_model']
        else:
            self.registry_model = None

        if 'instance' in kwargs and kwargs['instance'] is not None:
            instance = kwargs['instance']
            registry_specific_data = self._get_registry_specific_data(instance)
            wrapped_data = self._wrap_file_cdes(registry_specific_data)
            initial_data = kwargs.get('initial', {})
            for reg_code in wrapped_data:
                initial_data.update(wrapped_data[reg_code])

            self._update_initial_consent_data(instance, initial_data)

            kwargs['initial'] = initial_data

            clinicians = CustomUser.objects.filter(
                registry__in=kwargs['instance'].rdrf_registry.all())

        if "user" in kwargs:
            self.user = kwargs.pop("user")

        super(PatientForm,
              self).__init__(*args,
                             **kwargs)  # NB I have moved the constructor

        clinicians_filtered = [c.id for c in clinicians if c.is_clinician]
        self.fields["clinician"].queryset = CustomUser.objects.filter(
            id__in=clinicians_filtered)

        # clinicians field should only be visible for registries which
        # support linking of patient to an "owning" clinician
        if self.registry_model:
            if not self.registry_model.has_feature("clinicians_have_patients"):
                self.fields["clinician"].widget = forms.HiddenInput()

        registries = Registry.objects.all()
        if self.registry_model:
            registries = registries.filter(id=self.registry_model.id)
        self.fields["rdrf_registry"].queryset = registries

        if hasattr(self, 'user'):
            user = self.user
            # working groups shown should be only related to the groups avail to the
            # user in the registry being edited
            if not user.is_superuser:
                if self._is_parent_editing_child(instance):
                    # see FKRP #472
                    self.fields[
                        "working_groups"].widget = forms.SelectMultiple(
                            attrs={'readonly': 'readonly'})
                    self.fields[
                        "working_groups"].queryset = instance.working_groups.all(
                        )
                else:
                    self.fields[
                        "working_groups"].queryset = WorkingGroup.objects.filter(
                            registry=self.registry_model,
                            id__in=[
                                wg.pk for wg in self.user.working_groups.all()
                            ])
            else:
                self.fields[
                    "working_groups"].queryset = WorkingGroup.objects.filter(
                        registry=self.registry_model)

            # field visibility restricted no non admins
            if not user.is_superuser:
                if not self.registry_model:
                    registry = user.registry.all()[0]
                else:
                    registry = self.registry_model
                working_groups = user.groups.all()

                for field in self.fields:
                    hidden = False
                    readonly = False
                    for wg in working_groups:
                        try:
                            field_config = DemographicFields.objects.get(
                                registry=registry, group=wg, field=field)
                            hidden = hidden or field_config.hidden
                            readonly = readonly or field_config.readonly
                        except DemographicFields.DoesNotExist:
                            pass

                    if hidden:
                        self.fields[field].widget = forms.HiddenInput()
                        self.fields[field].label = ""
                    if readonly and not hidden:
                        self.fields[field].widget = forms.TextInput(
                            attrs={'readonly': 'readonly'})

        if self._is_adding_patient(kwargs):
            self._setup_add_form()

    def _is_parent_editing_child(self, patient_model):
        # see FKRP #472
        if patient_model is not None and hasattr(self, "user"):
            try:
                parent_guardian = ParentGuardian.objects.get(user=self.user)
                return patient_model in parent_guardian.children
            except ParentGuardian.DoesNotExist:
                pass

    def _get_registry_specific_data(self, patient_model):
        if patient_model is None:
            return {}
        mongo_wrapper = DynamicDataWrapper(patient_model)
        return mongo_wrapper.load_registry_specific_data(self.registry_model)

    def _wrap_file_cdes(self, registry_specific_data):
        from rdrf.forms.file_upload import FileUpload
        from rdrf.forms.file_upload import is_filestorage_dict
        from rdrf.helpers.utils import is_file_cde

        def wrap_file_cde_dict(registry_code, cde_code, filestorage_dict):
            return FileUpload(registry_code, cde_code, filestorage_dict)

        def wrap(registry_code, cde_code, value):
            if is_file_cde(cde_code) and is_filestorage_dict(value):
                return wrap_file_cde_dict(registry_code, cde_code, value)
            else:
                return value

        wrapped_dict = {}

        for reg_code in registry_specific_data:
            reg_data = registry_specific_data[reg_code]
            wrapped_data = {
                key: wrap(reg_code, key, value)
                for key, value in reg_data.items()
            }
            wrapped_dict[reg_code] = wrapped_data

        return wrapped_dict

    def _update_initial_consent_data(self, patient_model, initial_data):
        if patient_model is None:
            return
        data = patient_model.consent_questions_data
        for consent_field_key in data:
            initial_data[consent_field_key] = data[consent_field_key]

    def _is_adding_patient(self, kwargs):
        return 'instance' in kwargs and kwargs['instance'] is None

    def _setup_add_form(self):
        if hasattr(self, "user"):
            user = self.user
        else:
            user = None

        if not user.is_superuser:
            initial_working_groups = user.working_groups.filter(
                registry=self.registry_model)
            self.fields['working_groups'].queryset = initial_working_groups
        else:
            self.fields[
                'working_groups'].queryset = WorkingGroup.objects.filter(
                    registry=self.registry_model)

    date_of_birth = forms.DateField(widget=forms.DateInput(
        attrs={'class': 'datepicker'}, format='%d-%m-%Y'),
                                    help_text=_("DD-MM-YYYY"),
                                    input_formats=['%d-%m-%Y'])

    date_of_death = forms.DateField(widget=forms.DateInput(
        attrs={'class': 'datepicker'}, format='%d-%m-%Y'),
                                    help_text=_("DD-MM-YYYY"),
                                    input_formats=['%d-%m-%Y'],
                                    required=False)

    date_of_migration = forms.DateField(widget=forms.DateInput(
        attrs={'class': 'datepicker'}, format='%d-%m-%Y'),
                                        help_text=_("DD-MM-YYYY"),
                                        required=False,
                                        input_formats=['%d-%m-%Y'])

    class Meta:
        model = Patient
        widgets = {
            'next_of_kin_address': forms.Textarea(attrs={
                "rows": 3,
                "cols": 30
            }),
            'inactive_reason': forms.Textarea(attrs={
                "rows": 3,
                "cols": 30
            }),
            'user': forms.HiddenInput()
        }
        exclude = ['doctors']

    # Added to ensure unique (familyname, givennames, workinggroup)
    # Does not need a unique constraint on the DB

    def clean(self):
        self.custom_consents = {}
        cleaneddata = self.cleaned_data

        for k in cleaneddata:
            if k.startswith("customconsent_"):
                self.custom_consents[k] = cleaneddata[k]

        for k in self.custom_consents:
            del cleaneddata[k]

        if "working_groups" not in cleaneddata:
            raise forms.ValidationError(
                "Patient must be assigned to a working group")
        if not cleaneddata["working_groups"]:
            raise forms.ValidationError(
                "Patient must be assigned to a working group")

        self._check_working_groups(cleaneddata)

        self._validate_custom_consents()

        return super(PatientForm, self).clean()

    def _validate_custom_consents(self):
        data = {}
        for field_key in self.custom_consents:
            parts = field_key.split("_")
            reg_pk = int(parts[1])
            registry_model = Registry.objects.get(id=reg_pk)
            if registry_model not in data:
                data[registry_model] = {}

            consent_section_pk = int(parts[2])
            consent_section_model = ConsentSection.objects.get(
                id=int(consent_section_pk))

            if consent_section_model not in data[registry_model]:
                data[registry_model][consent_section_model] = {}

            consent_question_pk = int(parts[3])
            consent_question_model = ConsentQuestion.objects.get(
                id=consent_question_pk)
            answer = self.custom_consents[field_key]
            data[registry_model][consent_section_model][
                consent_question_model.code] = answer

        validation_errors = []

        for registry_model in data:
            for consent_section_model in data[registry_model]:

                answer_dict = data[registry_model][consent_section_model]
                if not consent_section_model.is_valid(answer_dict):
                    error_message = "Consent Section '%s %s' is not valid" % (
                        registry_model.code.upper(),
                        consent_section_model.section_label)
                    validation_errors.append(error_message)

        if len(validation_errors) > 0:
            raise forms.ValidationError("Consent Error(s): %s" %
                                        ",".join(validation_errors))

    def save(self, commit=True):
        patient_model = super(PatientForm, self).save(commit=False)
        patient_model.active = True
        try:
            patient_registries = [r for r in patient_model.rdrf_registry.all()]
        except ValueError:
            # If patient just created line above was erroring
            patient_registries = []

        if "user" in self.cleaned_data:
            patient_model.user = self.cleaned_data["user"]

        if commit:
            patient_model.save()
            patient_model.working_groups.set(
                self.cleaned_data["working_groups"])
            # for wg in self.cleaned_data["working_groups"]:
            #    patient_model.working_groups.add(wg)

            for reg in self.cleaned_data["rdrf_registry"]:
                patient_model.rdrf_registry.add(reg)

            patient_model.save()

        patient_model.clinician = self.cleaned_data["clinician"]

        for consent_field in self.custom_consents:
            registry_model, consent_section_model, consent_question_model = self._get_consent_field_models(
                consent_field)

            if registry_model in patient_registries:
                # are we still applicable?! - maybe some field on patient changed which
                # means not so any longer?
                if consent_section_model.applicable_to(patient_model):
                    patient_model.set_consent(
                        consent_question_model,
                        self.custom_consents[consent_field], commit)
            if not patient_registries:
                closure = self._make_consent_closure(registry_model,
                                                     consent_section_model,
                                                     consent_question_model,
                                                     consent_field)
                if hasattr(patient_model, 'add_registry_closures'):
                    patient_model.add_registry_closures.append(closure)
                else:
                    setattr(patient_model, 'add_registry_closures', [closure])

        return patient_model

    def _make_consent_closure(self, registry_model, consent_section_model,
                              consent_question_model, consent_field):
        def closure(patient_model, registry_ids):
            if registry_model.id in registry_ids:
                if consent_section_model.applicable_to(patient_model):
                    patient_model.set_consent(
                        consent_question_model,
                        self.custom_consents[consent_field])
            else:
                pass

        return closure

    def _check_working_groups(self, cleaned_data):
        def multiple_working_groups_allowed(reg_code):
            try:
                registry_model = Registry.objects.get(code=reg_code)
                return registry_model.has_feature(
                    "patients_multiple_working_groups")
            except Registry.DoesNotExist:
                return False

        working_group_data = {}
        for working_group in cleaned_data["working_groups"]:
            if working_group.registry:
                if working_group.registry.code not in working_group_data:
                    working_group_data[working_group.registry.code] = [
                        working_group
                    ]
                else:
                    working_group_data[working_group.registry.code].append(
                        working_group)

        bad = []
        for reg_code in working_group_data:
            if len(working_group_data[reg_code]
                   ) > 1 and not multiple_working_groups_allowed(reg_code):
                bad.append(reg_code)

        if bad:
            bad_regs = [
                Registry.objects.get(code=reg_code).name for reg_code in bad
            ]
            raise forms.ValidationError(
                "Patient can only belong to one working group per registry. Patient is assigned to more than one working for %s"
                % ",".join(bad_regs))
Esempio n. 15
0
class LayerForm(TranslationModelForm):
    date = forms.DateTimeField(widget=forms.SplitDateTimeWidget)
    date.widget.widgets[0].attrs = {
        "class": "datepicker",
        'data-date-format': "yyyy-mm-dd"
    }
    date.widget.widgets[1].attrs = {"class": "time"}
    temporal_extent_start = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "datepicker",
            'data-date-format': "yyyy-mm-dd"
        }))
    temporal_extent_end = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "datepicker",
            'data-date-format': "yyyy-mm-dd"
        }))

    poc = forms.ModelChoiceField(
        empty_label="Person outside GeoNode (fill form)",
        label="Point Of Contact",
        required=False,
        queryset=Profile.objects.exclude(username='******'),
        widget=autocomplete_light.ChoiceWidget('ProfileAutocomplete'))

    metadata_author = forms.ModelChoiceField(
        empty_label="Person outside GeoNode (fill form)",
        label="Metadata Author",
        required=False,
        queryset=Profile.objects.exclude(username='******'),
        widget=autocomplete_light.ChoiceWidget('ProfileAutocomplete'))

    keywords = taggit.forms.TagField(
        required=False,
        help_text=_("A space or comma-separated list of keywords"))

    regions = TreeNodeMultipleChoiceField(required=False,
                                          queryset=Region.objects.all(),
                                          level_indicator=u'___')
    regions.widget.attrs = {"size": 20}

    class Meta:
        model = Layer
        exclude = ('contacts', 'workspace', 'store', 'name', 'uuid',
                   'storeType', 'typename', 'bbox_x0', 'bbox_x1', 'bbox_y0',
                   'bbox_y1', 'srid', 'category', 'csw_typename', 'csw_schema',
                   'csw_mdsource', 'csw_type', 'csw_wkt_geometry',
                   'metadata_uploaded', 'metadata_xml', 'csw_anytext',
                   'popular_count', 'share_count', 'thumbnail',
                   'default_style', 'styles')
        widgets = autocomplete_light.get_widgets_dict(Layer)

    def __init__(self, *args, **kwargs):
        super(LayerForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            help_text = self.fields[field].help_text
            self.fields[field].help_text = None
            if help_text != '':
                self.fields[field].widget.attrs.update({
                    'class': 'has-popover',
                    'data-content': help_text,
                    'data-placement': 'right',
                    'data-container': 'body',
                    'data-html': 'true'
                })
 class Meta(UserCreationForm.Meta):
     model = CustomUser
     widgets = {'date_of_birth': forms.DateInput(attrs={'type': 'date'})}
Esempio n. 17
0
class ImportInvoiceForm(BootstrapMixin,forms.Form):
    file = forms.FileField()
    sheet_name = forms.CharField()
    date = forms.CharField(
        widget=forms.DateInput(
            attrs={'class':'ui-date-picker'}))
    due = forms.CharField(
        widget=forms.DateInput(
            attrs={'class':'ui-date-picker'}))
    customer = forms.ModelChoiceField(
        models.Customer.objects.all(),
        widget=Select2Widget
        )
    salesperson = forms.ModelChoiceField(
        models.SalesRepresentative.objects.all(),
        widget=Select2Widget
        )
    sales_tax = forms.ModelChoiceField(
        Tax.objects.all()
        )
    invoice_number = forms.IntegerField()
    
    description = forms.IntegerField()
    unit = forms.IntegerField()
    quantity = forms.IntegerField()
    unit_price = forms.IntegerField()
    subtotal = forms.IntegerField()
    
    start_row = forms.IntegerField()
    end_row = forms.IntegerField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            HTML('<h4>File</h4>'),
            Row(
                Column('file', css_class='col-6'),
                Column('sheet_name', css_class='col-6'),
            ),
            HTML('<h4>Invoice</h4>'),
            Row(
                Column('date', 'due', 'invoice_number',css_class='col-6'),
                Column('customer', 'salesperson', 'sales_tax',css_class='col-6'),
            ),
            
            HTML("""
            <h4>Columns</h4>
            <p>State the columns that correspond to the required data tp describe a customer .Convert alphabetic columns to numbers and insert below e.g. A=1, D=4 etc.</p>
            <ul>
                <li>Description - Name of product or service. Mark services with a '*' in the description cell. E.g. 'Bearing change' becomes '*Bearing change'.</li>
                <li>Unit - Unit of measure as it appears on invoice</li>
                <li>Quantity - One of Individual or Organization</li>
                <li>Unit Price - Price per item</li>
                <li>Subtotal - Total for the invoice line</li>
                
            </ul>"""),
            Row(
                Column('description', css_class='col-4'),
                Column('unit', css_class='col-2'),
                Column('quantity', css_class='col-2'),
                Column('unit_price', css_class='col-2'),
                Column('subtotal', css_class='col-2'),
            ),
            HTML("""
            <h4>Rows:</h4>
            <p>State the rows the list starts and ends in, both are inclusive.</p>"""),
            Row(
                Column('start_row', css_class='col-6'),
                Column('end_row', css_class='col-6'),
            ),
        )
        self.helper.add_input(Submit('submit', 'Submit'))
Esempio n. 18
0
class AddRoundForm(forms.Form):
    """
    """
    game = forms.CharField(label='Game:', max_length=50)
    date = forms.DateTimeField(
        label='Date:',
        input_formats=['%m/%d/%Y', '%Y-%m-%d'],
        widget=forms.DateInput(
            attrs={
                'class': 'form-control datetimepicker-input',
                'data-target': '#datetimepicker1',
                'type': 'date',
                'value': datetime.now().strftime("%Y-%m-%d")
            }))
    player = forms.CharField(label='Player:', required=False, max_length=50)
    players = forms.CharField(widget=forms.HiddenInput(), required=False)
    winners = forms.CharField(widget=forms.HiddenInput(), required=False)

    class Meta:
        model = Round
        fields = ('game', 'date', 'players', 'winners')

    def __init__(self, *args, **kwargs):
        """
        Add a specific class when generating the HTML code for easier styling.

        :param args: Form args
        :param kwargs: Form keyword args
        """
        super(AddRoundForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control autocomplete'

    def clean(self):
        """
        Clean the data provided by the user. Raise an error if the data is not proper.

        :return: The cleaned data
        """
        # Clean the data
        cleaned_data = super().clean()

        # Assign possible values
        game = cleaned_data.get('game')
        date = cleaned_data.get('date')
        players = cleaned_data.get('players')
        winners = cleaned_data.get('winners')

        print(players)

        if game:
            if date:
                if players:
                    if winners:
                        # TODO Everything exists, validate the content.
                        # Does the game exist?
                        # Is the date within the last year?
                        # Is the date not in the future?
                        # Are the players in this group?
                        # Is there a winner that isn't a player?

                        # Everything works!
                        return cleaned_data

                    raise forms.ValidationError("Winners are required")
                raise forms.ValidationError(
                    "Participating players are required")
            raise forms.ValidationError("Date is required")
        raise forms.ValidationError("Game name is required")
Esempio n. 19
0
class QueryResultForm(forms.Form):
    startStation = forms.ModelChoiceField(queryset=Station.objects.all(),
                                          required=True)
    endStation = forms.ModelChoiceField(queryset=Station.objects.all(),
                                        required=True)
    date = forms.DateField(required=True, widget=forms.DateInput())
Esempio n. 20
0
class PactPatientForm(Form):
    """
    DocumentForm
    """
    pactid = forms.CharField(label="PACT ID", required=True)

    first_name = forms.CharField(label="First Name", required=True)
    middle_name = forms.CharField(label="Middle Name", required=False)
    last_name = forms.CharField(label="Last Name", required=True)

    gender = forms.ChoiceField(label="Sex", choices=GENDER_CHOICES)
    #source: http://stackoverflow.com/questions/1513502/django-how-to-format-a-datefields-date-representation
    dob = forms.DateField(required=False,
                          label='DOB (m/d/y)',
                          input_formats=['%m/%d/%Y'],
                          widget=forms.DateInput(format='%m/%d/%Y',
                                                 attrs={'class': 'jqui-dtpk'}))
    race = forms.ChoiceField(choices=PACT_RACE_CHOICES)
    preferred_language = forms.ChoiceField(choices=PACT_LANGUAGE_CHOICES)

    mass_health_expiration = forms.DateField(
        label="Mass Health expiration date (m/d/y)",
        input_formats=['%m/%d/%Y', ''],
        widget=forms.DateInput(format='%m/%d/%Y'),
        required=False)
    ssn = forms.CharField(label="Social Security Number", required=False)

    hp = forms.ChoiceField(label="Primary health promoter", choices=())

    hp_status = forms.ChoiceField(label="HP Status",
                                  choices=PACT_HP_CHOICES,
                                  required=False)
    dot_status = forms.ChoiceField(label="DOT Status",
                                   choices=PACT_DOT_CHOICES,
                                   required=False)
    artregimen = forms.ChoiceField(choices=PACT_REGIMEN_CHOICES,
                                   required=False)
    nonartregimen = forms.ChoiceField(choices=PACT_REGIMEN_CHOICES,
                                      required=False)
    hiv_care_clinic = forms.ChoiceField(choices=PACT_HIV_CLINIC_CHOICES)

    patient_notes = forms.CharField(widget=widgets.Textarea(attrs={
        'cols': 80,
        'rows': 5
    }),
                                    required=False)

    def __init__(self, request, casedoc, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.casedoc = casedoc
        self.fields['hp'].choices = get_hp_choices()
        self.case_es = ReportCaseES(request.domain)
        for name, field in self.fields.items():
            if name == CASE_ART_REGIMEN_PROP:
                #these really should be a widget of some type
                #dereference the artregimen, dot_a_one...etc to become the comma separated regimen string for the form
                art_regimen_initial = self.casedoc.art_regimen_label_string()
                casedoc_value = art_regimen_initial
            elif name == CASE_NONART_REGIMEN_PROP:
                nonart_regimen_initial = self.casedoc.nonart_regimen_label_string(
                )
                casedoc_value = nonart_regimen_initial
            else:
                casedoc_value = getattr(self.casedoc, name, '')
            field.initial = casedoc_value

    @property
    def clean_changed_data(self):
        #to be called after validation
        ret = {}
        for name, value in self.cleaned_data.items():
            #to verify that the regimens changed calculate the dict of the freq+label ids.
            if name == CASE_ART_REGIMEN_PROP:
                art_props = regimen_dict_from_choice(DOT_ART, value)
                if art_props != self.casedoc.art_properties():
                    ret.update(art_props)
            elif name == CASE_NONART_REGIMEN_PROP:
                nonart_props = regimen_dict_from_choice(DOT_NONART, value)
                if nonart_props != self.casedoc.nonart_properties():
                    ret.update(nonart_props)
            else:
                if getattr(self.casedoc, name, '') != value:
                    ret[name] = value

        # hack, if any of the names, change remake the name and initials
        name_changed = False
        if 'first_name' in list(ret.keys()):
            name_changed = True
            first_name = ret['first_name']
        else:
            first_name = self.casedoc.first_name

        if 'last_name' in list(ret.keys()):
            name_changed = True
            last_name = ret['last_name']
        else:
            last_name = self.casedoc.last_name

        if name_changed:
            ret['name'] = '%s %s' % (first_name, last_name)
            ret['initials'] = '%s%s' % (
                first_name[0] if len(first_name) > 1 else '',
                last_name[0] if len(last_name) > 0 else '')

        return ret

    def clean_dob(self):
        if self.cleaned_data['dob'] is not None:
            return json_format_date(self.cleaned_data['dob'])
        else:
            return None

    def clean_mass_health_expiration(self):
        if self.cleaned_data['mass_health_expiration'] is not None:
            return json_format_date(
                self.cleaned_data['mass_health_expiration'])
        else:
            return None
Esempio n. 21
0
class EventsForm(forms.ModelForm):
    eventid = forms.CharField(
        max_length=15,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Event id"
        }))
    eventdate = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            "class": "form-control datepicker",
            'placeholder': "event date"
        }))
    eventtime = forms.TimeField(
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control timepicker",
            'placeholder': "event date"
        }))
    username = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "User Name"
        }))
    category = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Category"
        }))
    doorname = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Door Name"
        }))
    cardnumber = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Card Number"
        }))
    event = forms.CharField(max_length=25,
                            required=False,
                            widget=forms.TextInput(attrs={
                                "class": "form-control",
                                'placeholder': "Event"
                            }))
    action = forms.CharField(max_length=25,
                             required=False,
                             widget=forms.TextInput(attrs={
                                 "class": "form-control",
                                 'placeholder': "Action"
                             }))
    zonename = forms.CharField(
        max_length=25,
        required=False,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            'placeholder': "Action"
        }))

    class Meta:
        model = Events
        exclude = ['search_string']

    def save(self, commit=True):
        event = super(EventsForm, self).save(commit=False)
        event.search_string = event.eventid + " " + event.username + " " + event.category + " " + event.doorname
        event.save()
        return event
Esempio n. 22
0
class SignupForm(UserCreationForm):
    sUserID = forms.CharField(
        label="아이디  ",
        required=True,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': '아이디',
                'required': 'True',
            }
        )
    )
    name = forms.CharField(
        label="이름  ",
        max_length=30,                     
        widget=forms.TextInput(
            attrs={  
                'class': 'form-control',
                'placeholder': '이름',
                'required': 'true',
            }
        )
    )
    password1 = forms.CharField(
        label='비밀번호  ',
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '비밀번호',
                'required': 'True',
            }
        )
    )
    password2 = forms.CharField(
        label="비밀번호 확인  ",
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '비밀번호 확인',
                'required': 'True',
            }
        )
    )
    birthday = forms.DateField(
        label="생년월일  ",
        input_formats=
            ['%Y-%m-%d',
             '%Y/%m/%d',
             ],
        widget=forms.DateInput(
            attrs={
                'required': 'True',
                'readonly': 'True',
                'style': "background-image:url('/static/first/images/calendar1.png'); background-repeat: no-repeat; background-position: center;",
                'onselect' : 'focusCalendar()',
                }
        )
    )
    SEX = [
        ('M','남자'),
        ('F','여자')
    ]
    sex = forms.ChoiceField(
        label = "성별  ",
        choices = SEX,
        widget = forms.RadioSelect()
    )
    phone = forms.CharField(
        label="핸드폰  ",
        max_length=20,                     
        widget=forms.TextInput(
            attrs={  
                'class': 'form-control',
                'placeholder': '010-0000-0000',
                'required': 'true',
                'onselect' : 'focusPhone()',
                'onclick' : 'focusPhone()',
            }
        )
    )
    MARRIED = [
        ('T','기혼'),
        ('F','미혼')
    ]
    married = forms.ChoiceField(
        label = "결혼 여부  ",
        choices = MARRIED,
        widget = forms.RadioSelect()
    )
    CHILDREN = [
        ('T','자녀 있음'),
        ('F','자녀 없음')
    ]
    children = forms.ChoiceField(
        label = "자녀 유무  ",
        choices = CHILDREN,
        widget = forms.RadioSelect()
    )
    job = forms.CharField(
        label = "직업  ",
        max_length=30,                     
        widget=forms.TextInput(
            attrs={  
                'class': 'form-control',
                'placeholder': '직업',
                'required': 'true',
            }
        )
    )
    company = forms.CharField(
        label = "직장  ",
        max_length=30,                     
        widget=forms.TextInput(
            attrs={  
                'class': 'form-control',
                'placeholder': '직장',
                'required': 'true',
            }
        )
    )
    hobby = forms.CharField(
        label = "취미  ",
        max_length=30,                     
        widget=forms.TextInput(
            attrs={  
                'class': 'form-control',
                'placeholder': '취미',
                'required': 'true',
            }
        )
    )

    class Meta: # SignupForm에 대한 기술서
        model = SUser
        fields = ("sUserID", "name", "password1", "password2",
                  "birthday", "sex", "phone", "married", "children",
                  "job", "company", "hobby") # 작성한 필드만큼 화면에 보여짐
Esempio n. 23
0
class CoreLogSearchForm(forms.Form):
    action = forms.ChoiceField(label=u'操作类型', choices=ACTION_TYPE, required=False)
    date_start = forms.DateField(label=u'开始日期', required=False,
                           widget=forms.DateInput(attrs={'class': 'dateinput', 'readonly': 'readonly', 'size': 12}))
    date_end = forms.DateField(label=u'结束日期', required=False,
                           widget=forms.DateInput(attrs={'class': 'dateinput', 'readonly': 'readonly', 'size': 12}))
Esempio n. 24
0
class MeetingForm(forms.Form):
    # Value to tell if this is being created or is an edit
    edit = forms.BooleanField(
        label='edit',
        initial=False,
        required=False,
        widget=forms.HiddenInput(),
    )
    endpoint = forms.CharField(
        label='Endpoint (Unique, short id)',
        required=True,
    )
    name = forms.CharField(
        label='Conference name',
        required=True,
        widget=forms.TextInput(attrs={'size': '40'}),
    )
    info_url = forms.CharField(
        label='Info url',
        required=False,
        widget=forms.TextInput(attrs={'size': '60'}),
    )
    homepage_link_text = forms.CharField(
        label='Homepage link text (Default: "Conference homepage")',
        required=False,
        widget=forms.TextInput(attrs={'size': '60'}),
    )
    location = forms.CharField(
        label='Location',
        required=False,
    )
    start_date = forms.DateField(
        widget=forms.DateInput(format='%b %d %Y'),
        required=False,
        label='Start date (e.g. Nov 7 2016)'
    )
    end_date = forms.DateField(
        widget=forms.DateInput(format='%b %d %Y'),
        required=False,
        label='End date (e.g. Nov 9 2016)'
    )
    logo_url = forms.CharField(
        label='Logo url',
        required=False,
        widget=forms.TextInput(attrs={'size': '60'}),
    )
    is_meeting = forms.BooleanField(
        label='This is a meeting',
        initial=True,
        required=False,
    )
    active = forms.BooleanField(
        label='Conference is active',
        required=False,
        initial=True,
    )
    admins = MultiEmailField(
        label='Conference administrator emails (comma separated)',
        widget=forms.TextInput(attrs={'size': '50'}),
        required=False,
    )
    public_projects = forms.BooleanField(
        label='Projects are public',
        required=False,
        initial=True,
    )
    poster = forms.BooleanField(
        label='Posters',
        required=False,
        initial=True,
    )
    talk = forms.BooleanField(
        label='Talks',
        required=False,
        initial=True,
    )
    submission1 = forms.CharField(
        label='Name for Submission 1 (poster)'
    )
    submission2 = forms.CharField(
        label='Name for Submission 2 (talk)'
    )
    submission1_plural = forms.CharField(
        label='Plural for submission 1'
    )
    submission2_plural = forms.CharField(
        label='Plural for submission 2'
    )
    meeting_title_type = forms.CharField(
        label='Title for the type of meeting'
    )
    add_submission = forms.CharField(
        label='Add submission'
    )
    mail_subject = forms.CharField(
        label='Mail subject'
    )
    mail_message_body = forms.CharField(
        label='Message body for mail',
        widget=forms.TextInput(attrs={'size': '60'}),
    )
    mail_attachment = forms.CharField(
        label='Mail attachment message',
        widget=forms.TextInput(attrs={'size': '60'}),
    )

    def clean_start_date(self):
        date = self.cleaned_data.get('start_date')
        if date is not None:
            return datetime.combine(date, datetime.min.time())

    def clean_end_date(self):
        date = self.cleaned_data.get('end_date')
        if date is not None:
            return datetime.combine(date, datetime.min.time())

    def clean_endpoint(self):
        endpoint = self.cleaned_data['endpoint']
        edit = self.cleaned_data['edit']
        try:
            Conference.get_by_endpoint(endpoint, False)
            if not edit:
                raise forms.ValidationError(
                    'A meeting with this endpoint exists already.'
                )
        except ConferenceError:
            if edit:
                raise forms.ValidationError(
                    'Meeting not found with this endpoint to update'
                )
        return endpoint

    def clean_admins(self):
        emails = self.cleaned_data['admins']
        for email in emails:
            user = get_user(email=email)
            if not user or user is None:
                raise forms.ValidationError(
                    '{} does not have an OSF account'.format(email)
                )
        return emails
Esempio n. 25
0
    def __init__(self, last_added, *args, **kwargs):
        super(EditAddedDatesForm, self).__init__(*args, **kwargs)
        i = 1
        for date in last_added:
            self.fields['id_%s' % i] = forms.CharField(
                label="Id",
                initial=date.id,
                widget=forms.TextInput(
                    attrs={
                        'readonly': 'True',
                        'hidden': 'hidden',
                        'class': 'edit_dates_field_id'
                    }))
            self.fields['date_%s' % i] = forms.DateField(
                label="Data",
                initial=date.date,
                input_formats='%Y-%m-%d',
                widget=forms.DateInput(attrs={
                    'readonly': 'True',
                    'class': 'edit_dates_field_date'
                }))
            self.fields['begin_%s' % i] = forms.TimeField(
                label="Od",
                initial=date.begin,
                input_formats='%H:%M:%S',
                widget=forms.TextInput(
                    attrs={'class': 'edit_dates_field_begin'}))
            self.fields['end_%s' % i] = forms.TimeField(
                label="Do",
                initial=date.end,
                input_formats='%H:%M:%S',
                widget=forms.TextInput(
                    attrs={'class': 'edit_dates_field_end'}))
            self.fields['dentist_%s' % i] = forms.CharField(
                label="Dentysta",
                initial=date.dentist,
                widget=forms.TextInput(attrs={
                    'readonly': 'True',
                    'class': 'edit_dates_field_dentist'
                }))
            self.fields['dental_office_%s' % i] = forms.CharField(
                label="Gabinet",
                initial=date.dental_office,
                widget=forms.TextInput(
                    attrs={
                        'readonly': 'True',
                        'class': 'edit_dates_field_dental_office'
                    }))
            self.fields['room_%s' % i] = forms.CharField(
                label="Pokój",
                initial=date.room,
                widget=forms.TextInput(attrs={
                    'class': 'edit_dates_field_room',
                    'maxlength': '5'
                }))
            i += 1

        self.fields['number_of_fields'] = forms.CharField(
            label="Liczba dat",
            initial=i - 1,
            widget=forms.TextInput(
                attrs={
                    'readonly': 'True',
                    'hidden': 'hidden',
                    'class': 'edit_dates_field_number'
                }))
Esempio n. 26
0
class ExperimentTimelinePopulationForm(ChangeLogMixin, forms.ModelForm):
    proposed_start_date = forms.DateField(
        required=False,
        label="Proposed Start Date",
        help_text=Experiment.PROPOSED_START_DATE_HELP_TEXT,
        widget=forms.DateInput(attrs={
            "type": "date",
            "class": "form-control"
        }),
    )
    proposed_duration = forms.IntegerField(
        required=False,
        min_value=1,
        label="Proposed Total Duration (days)",
        help_text=Experiment.PROPOSED_DURATION_HELP_TEXT,
        widget=forms.NumberInput(attrs={"class": "form-control"}),
    )
    proposed_enrollment = forms.IntegerField(
        required=False,
        min_value=1,
        label="Proposed Enrollment Duration (days)",
        help_text=Experiment.PROPOSED_ENROLLMENT_HELP_TEXT,
        widget=forms.NumberInput(attrs={"class": "form-control"}),
    )
    rollout_playbook = forms.ChoiceField(
        required=False,
        label="Rollout Playbook",
        choices=Experiment.ROLLOUT_PLAYBOOK_CHOICES,
        widget=forms.Select(attrs={"class": "form-control"}),
        help_text=Experiment.ROLLOUT_PLAYBOOK_HELP_TEXT,
    )
    population_percent = forms.DecimalField(
        required=False,
        label="Population Percentage",
        help_text=Experiment.POPULATION_PERCENT_HELP_TEXT,
        initial="0.00",
        widget=forms.NumberInput(attrs={"class": "form-control"}),
    )
    firefox_min_version = forms.ChoiceField(
        required=False,
        choices=Experiment.MIN_VERSION_CHOICES,
        widget=forms.Select(attrs={"class": "form-control"}),
        help_text=Experiment.VERSION_HELP_TEXT,
    )
    firefox_max_version = forms.ChoiceField(
        required=False,
        choices=Experiment.MAX_VERSION_CHOICES,
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    firefox_channel = forms.ChoiceField(
        required=False,
        choices=Experiment.CHANNEL_CHOICES,
        widget=forms.Select(attrs={"class": "form-control"}),
        label="Firefox Channel",
        help_text=Experiment.CHANNEL_HELP_TEXT,
    )
    locales = CustomModelMultipleChoiceField(
        required=False,
        label="Locales",
        all_label="All locales",
        help_text="Applicable only if you don't select All",
        queryset=Locale.objects.all(),
        to_field_name="code",
    )
    countries = CustomModelMultipleChoiceField(
        required=False,
        label="Countries",
        all_label="All countries",
        help_text="Applicable only if you don't select All",
        queryset=Country.objects.all(),
        to_field_name="code",
    )
    platform = forms.ChoiceField(
        required=False,
        label="Platform",
        help_text=Experiment.PLATFORM_HELP_TEXT,
        choices=Experiment.PLATFORM_CHOICES,
        widget=forms.Select(attrs={"class": "form-control"}),
    )
    client_matching = forms.CharField(
        required=False,
        label="Population Filtering",
        help_text=Experiment.CLIENT_MATCHING_HELP_TEXT,
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "rows": 10
        }),
    )
    # See https://developer.snapappointments.com/bootstrap-select/examples/
    # for more options that relate to the initial rendering of the HTML
    # as a way to customize how it works.
    locales.widget.attrs.update({"data-live-search": "true"})
    countries.widget.attrs.update({"data-live-search": "true"})

    class Meta:
        model = Experiment
        fields = [
            "proposed_start_date",
            "proposed_duration",
            "proposed_enrollment",
            "rollout_playbook",
            "population_percent",
            "firefox_min_version",
            "firefox_max_version",
            "firefox_channel",
            "locales",
            "countries",
            "platform",
            "client_matching",
        ]

    def __init__(self, *args, **kwargs):
        data = kwargs.pop("data", None)
        instance = kwargs.pop("instance", None)
        if instance:
            # The reason we must do this is because the form fields
            # for locales and countries don't know about the instance
            # not having anything set, and we want the "All" option to
            # appear in the generated HTML widget.
            kwargs.setdefault("initial", {})
            if not instance.locales.all().exists():
                kwargs["initial"]["locales"] = [
                    CustomModelMultipleChoiceField.ALL_KEY
                ]
            if not instance.countries.all().exists():
                kwargs["initial"]["countries"] = [
                    CustomModelMultipleChoiceField.ALL_KEY
                ]
        super().__init__(data=data, instance=instance, *args, **kwargs)

    def clean_population_percent(self):
        population_percent = self.cleaned_data.get("population_percent")

        if population_percent and not (0 < population_percent <= 100):
            raise forms.ValidationError(
                "The population size must be between 0 and 100 percent.")

        return population_percent

    def clean_firefox_max_version(self):
        firefox_min_version = self.cleaned_data.get("firefox_min_version")
        firefox_max_version = self.cleaned_data.get("firefox_max_version")

        if firefox_min_version and firefox_max_version:
            if firefox_max_version < firefox_min_version:
                raise forms.ValidationError(
                    "The max version must be larger than or equal to the min version."
                )

            return firefox_max_version

    def clean_proposed_start_date(self):
        start_date = self.cleaned_data.get("proposed_start_date")

        if start_date and start_date < timezone.now().date():
            raise forms.ValidationError(
                "The delivery start date must be no earlier than the current date."
            )

        return start_date

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

        # enrollment may be None
        enrollment = cleaned_data.get("proposed_enrollment")
        duration = cleaned_data.get("proposed_duration")

        if (enrollment and duration) and enrollment > duration:
            msg = ("Enrollment duration is optional, but if set, "
                   "must be lower than the delivery duration. "
                   "If enrollment duration is not specified - users "
                   "are enrolled for the entire delivery.")
            self._errors["proposed_enrollment"] = [msg]

        return cleaned_data

    def save(self, *args, **kwargs):
        experiment = super().save(*args, **kwargs)

        if self.instance.is_rollout:
            rollout_size = self.instance.rollout_dates.get(
                "first_increase") or self.instance.rollout_dates.get(
                    "final_increase")

            if rollout_size:
                experiment.population_percent = decimal.Decimal(
                    rollout_size["percent"])
                experiment.save()

        return experiment
Esempio n. 27
0
class AttendanceHistoryByDateForm(forms.Form):
    date = forms.DateField(widget=forms.DateInput(attrs={'type':'date','class': 'form-control', 'required': True}))
Esempio n. 28
0
 class Meta:
     model = Item
     fields = ['title', 'number', 'effective_date', 'description']
     widgets = {
         'effective_date': forms.DateInput(attrs={'type': 'date'}),
     }
Esempio n. 29
0
class Teacher_personal_detailform(forms.ModelForm):
    """Upload files with this form"""
    dob = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',))

    class Meta:
        model = Teacher_personal_detail
Esempio n. 30
0
class UserRegisterForm(forms.ModelForm):
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'placeholder': ' First Name',
            'class': "form-control form-control-sm"
        }),
        max_length=50,
        required=True)
    last_name = forms.CharField(
        widget=forms.TextInput(attrs={
            'placeholder': ' Last Name',
            'class': "form-control form-control-sm"
        }),
        max_length=50,
        required=True)
    company = forms.CharField(
        widget=forms.TextInput(attrs={
            'placeholder': ' Company',
            'class': "form-control form-control-sm"
        }),
        max_length=55,
        required=False)
    dob = forms.DateField(widget=forms.DateInput(
        attrs={
            'type': 'date',
            'class': "form-control form-control-sm"
        }))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'placeholder': 'password',
            'class': "form-control form-control-sm"
        }),
        required=False)
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'placeholder': ' Email',
            'class': "form-control form-control-sm"
        }),
        required=True)
    address = forms.CharField(widget=forms.Textarea(
        attrs={
            'placeholder': ' Address',
            'cols': 20,
            'rows': 5,
            'class': "form-control form-control-sm"
        }),
                              required=False)

    class Meta:
        model = Users
        fields = ('first_name', 'last_name', 'company', 'dob', 'password',
                  'email', 'address')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        user = Users.objects.filter(email=email).exists()
        if user:
            raise forms.ValidationError('Email is already registered')
        return email

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if password and len(password) < 8:
            raise forms.ValidationError(
                'Password must be at least 8 characters long!')
        return password