Ejemplo n.º 1
0
class ScenarioForm(FeatureForm):
    description = forms.CharField(widget=forms.Textarea(attrs={
        'cols': 30,
        'rows': 3
    }),
                                  required=False)

    support_file = ValidFileField(widget=AdminFileWidget,
                                  required=False,
                                  label="Support File")
    #could optionally add a param similar to the following:  help_text="(e.g. a pdf or text document that explains this scenario)"

    # GeoPhysical

    input_parameter_depth = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_min_depth = forms.FloatField(
        initial=10, widget=forms.TextInput(attrs={'class': 'slidervalue'}))
    input_max_depth = forms.FloatField(
        initial=50, widget=forms.TextInput(attrs={'class': 'slidervalue'}))
    input_depth = forms.FloatField(widget=DualSliderWidget('input_min_depth',
                                                           'input_max_depth',
                                                           min=10,
                                                           max=100,
                                                           step=5),
                                   required=False)

    input_parameter_distance_to_shore = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_min_distance_to_shore = forms.FloatField(
        initial=12, widget=forms.TextInput(attrs={'class': 'slidervalue'}))
    input_max_distance_to_shore = forms.FloatField(
        initial=50, widget=forms.TextInput(attrs={'class': 'slidervalue'}))
    input_distance_to_shore = forms.FloatField(widget=DualSliderWidget(
        'input_min_distance_to_shore',
        'input_max_distance_to_shore',
        min=3,
        max=100,
        step=1),
                                               required=False)

    input_parameter_substrate = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_substrate = ModelMultipleChoiceField(
        queryset=Substrate.objects.all().order_by('substrate_id'),
        widget=CheckboxSelectMultiple(attrs={'class': 'substrate_checkboxes'}),
        required=False)

    input_parameter_sediment = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_sediment = ModelMultipleChoiceField(
        queryset=Sediment.objects.all().order_by('sediment_id'),
        widget=CheckboxSelectMultiple(attrs={'class': 'sediment_checkboxes'}),
        required=False)

    # Wind Energy

    #TODO:  might adjust the max_value to 21.5 (this is the max min value, don't yet have the avg value...)
    input_parameter_wind_speed = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_avg_wind_speed = forms.FloatField(
        min_value=7,
        max_value=9.5,
        initial=8,
        #widget=SliderWidgetWithTooltip( min=10,max=21.5,step=.1,
        #id="info_wind_speed_widget"),
        widget=SliderWidget(min=7, max=9.5, step=.25),
        required=False)

    input_parameter_distance_to_awc = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_distance_to_awc = forms.FloatField(min_value=1,
                                             max_value=30,
                                             initial=15,
                                             widget=SliderWidget(min=1,
                                                                 max=30,
                                                                 step=1),
                                             required=False)

    input_parameter_distance_to_substation = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_distance_to_substation = forms.FloatField(
        min_value=10,
        max_value=50,
        initial=30,
        widget=SliderWidget(min=10, max=50, step=1),
        required=False)

    input_parameter_wea = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    #input_parameter_wea_choice = forms.ChoiceField( widget=RadioSelect(attrs={'class': 'parameters'}), choices=WEA_CHOICES, required=False )
    input_wea = ModelMultipleChoiceField(
        queryset=WEA.objects.all().order_by('wea_id'),
        widget=CheckboxSelectMultiple(attrs={'class': 'wea_checkboxes'}),
        required=False)

    # Shipping

    input_filter_ais_density = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'filters'}), required=False)
    #input_traffic_density = forms.FloatField(   min_value=1, max_value=3, initial=2,
    #                                            widget=SliderWidget( min=1, max=3, step=1, show_number=False),
    #                                            required=False)

    input_filter_distance_to_shipping = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_distance_to_shipping = forms.FloatField(min_value=1,
                                                  max_value=10,
                                                  initial=3,
                                                  widget=SliderWidget(min=1,
                                                                      max=10,
                                                                      step=1),
                                                  required=False)

    # NON-ACTIVATED FORM ELEMENTS

    input_assessment_areas = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_warn_areas = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)
    input_ordinance_areas = forms.BooleanField(
        widget=CheckboxInput(attrs={'class': 'parameters'}), required=False)

    #lease_blocks = ModelMultipleChoiceField( queryset=LeaseBlock.objects.all().order_by('id'), required=False)

    def save(self, commit=True):
        inst = super(FeatureForm, self).save(commit=False)
        if self.data.get('clear_support_file'):
            inst.support_file = None
        if commit:
            inst.save()
        return inst

    class Meta(FeatureForm.Meta):
        model = Scenario
        exclude = list(FeatureForm.Meta.exclude)
        for f in model.output_fields():
            exclude.append(f.attname)
Ejemplo n.º 2
0
 class BulkDeleteForm(ConfirmationForm):
     pk = ModelMultipleChoiceField(queryset=self.queryset,
                                   widget=MultipleHiddenInput)
Ejemplo n.º 3
0
class ContestTagForm(ModelForm):
    contests = ModelMultipleChoiceField(
        label=_('Included contests'),
        queryset=Contest.objects.all(),
        required=False,
        widget=AdminHeavySelect2MultipleWidget(data_view='contest_select2'))
Ejemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        """ Impcap/Log Darwin policy """
        self.fields['darwin_policy'] = ModelChoiceField(
            label=_("Darwin policy"),
            queryset=DarwinPolicy.objects.all(),
            widget=Select(attrs={'class': 'form-control select2'}),
            required=False)
        """ Log forwarders """
        self.fields['log_forwarders'] = ModelMultipleChoiceField(
            label=_("Log forwarders"),
            queryset=LogOM.objects.all().only(*LogOM.str_attrs()),
            widget=SelectMultiple(attrs={'class': 'form-control select2'}),
            required=False)
        """ Log forwarders """
        self.fields['log_forwarders_parse_failure'] = ModelMultipleChoiceField(
            label=_("Log forwarders - parse failure"),
            queryset=LogOM.objects.all().only(*LogOM.str_attrs()),
            widget=SelectMultiple(attrs={'class': 'form-control select2'}),
            required=False)
        """ MMDP Reputation database IPv4 """
        # Defined here AND in model, to use queryset
        self.fields['logging_reputation_database_v4'] = ModelChoiceField(
            label=_("Rsyslog IPv4 reputation database"),
            # queryset=[(f.get('id'), str(f)) for f in Feed.objects.mongo_find({"filename": {"$regex": r"\.mmdb$"},  # MMDB database
            #                                   "label": {"$regex": r"^((?![iI][Pp][Vv]6).)*$"}},  # Excude IPv6
            #                                  {"filename": 1, "label": 1})],  # .only( label, filename )
            # queryset=Feed.objects.filter(filename__iregex="^((?![iI][Pp][Vv]6).)*\.mmdb$"),
            # queryset=Feed.objects.exclude(filename__iregex="^((?![iI][Pp][Vv]6).)*$").filter(filename__endswith=".mmdb"),
            queryset=ReputationContext.objects.filter(
                db_type="ipv4", filename__endswith=".mmdb").only(
                    *(ReputationContext.str_attrs() +
                      ['filename', 'db_type'])),
            widget=Select(attrs={'class': 'form-control select2'}),
            empty_label="No IPv4",
            required=False)
        """ MMDP Reputation database IPv6 """
        # Defined here AND in model, to use queryset
        self.fields['logging_reputation_database_v6'] = ModelChoiceField(
            label=_("Rsyslog IPv6 reputation database"),
            queryset=ReputationContext.objects.filter(
                db_type="ipv6",
                filename__endswith=".mmdb")  # MMDP database & IPv6
            .only(*(ReputationContext.str_attrs() + ['filename', 'db_type'])),
            widget=Select(attrs={'class': 'form-control select2'}),
            empty_label="No IPv6",
            required=False)
        self.fields['logging_geoip_database'] = ModelChoiceField(
            label=_("Rsyslog GeoIP database"),
            queryset=ReputationContext.objects.filter(db_type="GeoIP").only(
                *(ReputationContext.str_attrs() + ['filename', 'db_type'])),
            widget=Select(attrs={'class': 'form-control select2'}),
            empty_label="No GeoIP",
            required=False)

        self.fields['node'] = ModelChoiceField(
            label=_('Node'),
            queryset=Node.objects.all(),
            widget=Select(attrs={'class': 'form-control select2'}))

        # Remove the blank input generated by django
        for field_name in [
                'mode', 'ruleset', 'log_level', 'listening_mode',
                'compression_algos', 'log_forwarders', 'impcap_intf'
        ]:
            self.fields[field_name].empty_label = None
        self.fields['error_template'].empty_label = "No template"
        # Set required in POST data to False
        for field_name in [
                'log_condition', 'ruleset', 'log_level', 'listening_mode',
                'headers', 'custom_haproxy_conf', 'cache_total_max_size',
                'cache_max_age', 'compression_algos', 'compression_mime_types',
                'error_template', 'enable_logging_reputation', 'impcap_filter',
                'impcap_filter_type', 'impcap_intf', 'tags', 'timeout_client',
                'timeout_connect', 'timeout_keep_alive', 'parser_tag',
                'file_path', 'node'
        ]:
            self.fields[field_name].required = False
        """ Build choices of "ruleset" field with rsyslog jinja templates names """
        # read the entries
        try:
            with scandir(JINJA_RSYSLOG_PATH) as listOfEntries:
                for entry in listOfEntries:
                    if entry.is_dir():
                        m = re_search("rsyslog_ruleset_([\w-]+)", entry.name)
                        if m:
                            # Do NOT process haproxy - it's an internal log type
                            if m.group(1) in ("haproxy", "haproxy_tcp"):
                                continue
                            self.fields['ruleset'].widget.choices.append(
                                (m.group(1), m.group(1)))
        except Exception as e:
            logger.error(
                "Cannot build 'ruleset' choices. Seems that path '{}' is not found: "
                .format(JINJA_RSYSLOG_PATH))
            logger.exception(e)

        # Set initial value of compression_algos field,
        #  convert space separated string into list
        if self.initial.get('compression_algos'):
            self.initial['compression_algos'] = self.initial.get(
                'compression_algos').split(' ')
        self.initial['tags'] = ','.join(
            self.initial.get('tags', []) or self.fields['tags'].initial)
Ejemplo n.º 5
0
class G3WUserForm(G3WRequestFormMixin, G3WFormMixin, FileFormMixin,
                  UserCreationForm):

    department = ModelChoiceField(queryset=Department.objects.all(),
                                  required=False)
    backend = ChoiceField(choices=USER_BACKEND_TYPES)
    avatar = UploadedFileField(required=False)

    groups = ModelMultipleChoiceField(
        queryset=AuthGroup.objects.filter(
            name__in=[G3W_EDITOR1, G3W_EDITOR2, G3W_VIEWER1]),
        required=True,
        help_text=_('Select roles for this user'),
        label=_('Main roles'))

    user_groups_editor = ModelMultipleChoiceField(
        queryset=AuthGroup.objects.filter(
            ~Q(name__in=[G3W_EDITOR1, G3W_EDITOR2, G3W_VIEWER1, G3W_VIEWER2]),
            grouprole__role='editor'),
        required=False,
        help_text=
        _('Select <b>EDITOR groups</b> for this user, only Editor Level 2 can be added'
          ),
        label=_('User editor groups'))

    user_groups_viewer = ModelMultipleChoiceField(
        queryset=AuthGroup.objects.filter(
            ~Q(name__in=[G3W_EDITOR1, G3W_EDITOR2, G3W_VIEWER1, G3W_VIEWER2]),
            grouprole__role='viewer'),
        required=False,
        help_text=
        _('Select <b>VIEWER groups</b> for this user, only Viewer Level 1 can be added'
          ),
        label=_('User viewer groups'))

    def _set_editor1_queryset(self):
        """
        Set correct guardian queryset for editor level 1
        """
        self.fields['user_groups_editor'].queryset = get_objects_for_user(
            self.request.user, 'auth.change_group',
            AuthGroup).order_by('name').filter(grouprole__role='editor')
        self.fields['user_groups_viewer'].queryset = get_objects_for_user(
            self.request.user, 'auth.change_group',
            AuthGroup).order_by('name').filter(grouprole__role='viewer')

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

        #filter fileds by role:
        self.filterFieldsByRoles(**kwargs)

        #check for groups in intials data
        if 'groups' in self.initial and len(self.initial['groups']) > 0:
            self.initial['groups'] = self.initial['groups']

        if 'user_groups' in self.initial and len(
                self.initial['user_groups']) > 0:
            self.initial['user_groups'] = self.initial['user_groups']

        # change queryset for editor1
        if G3W_EDITOR1 in getUserGroups(self.request.user):
            self._set_editor1_queryset()

        self.helper = FormHelper(self)
        self.helper.form_tag = False

        args = [
            Div(Div(Div(Div(HTML(
                "<h3 class='box-title'><i class='fa fa-file'></i> {}</h3>".
                format(_('Anagraphic'))),
                            css_class='box-header with-border'),
                        Div(
                            'first_name',
                            'last_name',
                            'email',
                            css_class='box-body',
                        ),
                        css_class='box box-success'),
                    css_class='col-md-6'),
                Div(Div(Div(HTML(
                    "<h3 class='box-title'><i class='fa fa-users'></i> {}</h3>"
                    .format(_('ACL/Roles'))),
                            css_class='box-header with-border'),
                        Div(*self.__authrole_fields(), css_class='box-body'),
                        css_class='box box-solid bg-teal-gradient'),
                    css_class='col-md-6 {}'.format(
                        self.checkFieldsVisible('is_superuser', 'is_staff',
                                                'groups'))),
                css_class='row'),
            Div(Div(Div(Div(HTML(
                "<h3 class='box-title'><i class='fa fa-lock'></i> {}</h3>".
                format(_('Login data'))),
                            css_class='box-header with-border'),
                        Div(
                            PrependedText('username',
                                          '<i class="fa fa-user"></i>'),
                            PrependedText('password1',
                                          '<i class="fa fa-lock"></i>'),
                            PrependedText('password2',
                                          '<i class="fa fa-lock"></i>'),
                            css_class='box-body',
                        ),
                        css_class='box box-danger'),
                    css_class='col-md-6'),
                Div(Div(
                    Div(
                        HTML(
                            "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>"
                            .format(_('User data'))),
                        css_class='box-header with-border'),
                    Div(
                        'department',
                        'avatar',
                        HTML(
                            """{% if form.avatar.value %}<img class="img-responsive img-thumbnail" src="{{ MEDIA_URL }}{{ form.avatar.value }}">{% endif %}""",
                        ),
                        'form_id',
                        'upload_url',
                        'delete_url',
                        css_class='box-body',
                    ),
                    css_class='box box-default'),
                    css_class='col-md-6'),
                css_class='row')
        ]

        # add backed if user id admin01
        if self.request.user.is_superuser and self.request.user.is_staff:
            args.append(
                Div(Div(Div(Div(HTML(
                    "<h3 class='box-title'><i class='fa fa-gear'></i> {}</h3>".
                    format(_('User backend'))),
                                css_class='box-header with-border'),
                            Div(
                                'backend',
                                css_class='box-body',
                            ),
                            css_class='box box-default'),
                        css_class='col-md-6'),
                    css_class='row'))

        self.helper.layout = Layout(*args)

    def __authrole_fields(self):
        """ Get fields for ACL box if they are into self.fields """

        fields = []
        if 'is_superuser' in self.fields:
            fields.append('is_superuser')

        if 'is_staff' in self.fields:
            fields.append('is_staff')

        if 'groups' in self.fields:
            fields.append(
                Field(
                    'groups', **{
                        'css_class': 'select2 col-md-12',
                        'multiple': 'multiple',
                        'style': 'width:100%;'
                    }))

        if 'user_groups_editor' in self.fields:
            fields.append(
                Field(
                    'user_groups_editor', **{
                        'css_class': 'select2 col-md-12',
                        'multiple': 'multiple',
                        'style': 'width:100%;'
                    }))

        if 'user_groups_viewer' in self.fields:
            fields.append(
                Field(
                    'user_groups_viewer', **{
                        'css_class': 'select2 col-md-12',
                        'multiple': 'multiple',
                        'style': 'width:100%;'
                    }))

        return fields

    def filterFieldsByRoles(self, **kwargs):
        if self.request.user.is_superuser:
            if not self.request.user.is_staff:
                self.fields.pop('is_staff')
                self.fields.pop('backend')
        elif G3W_EDITOR1 in getUserGroups(self.request.user):
            # other but only Editor level 1 can add user
            # if user is not himself
            if 'instance' in kwargs and kwargs['instance'] == self.request.user:
                self.fields.pop('groups')
            else:
                self.fields['groups'].queryset = AuthGroup.objects.filter(
                    name__in=[G3W_EDITOR2, G3W_VIEWER1])
                self.fields['groups'].required = True
            self.fields.pop('is_superuser')
            self.fields.pop('is_staff')
            self.fields.pop('backend')
        else:
            self.fields.pop('is_superuser')
            self.fields.pop('is_staff')
            self.fields.pop('groups')
            self.fields.pop('department')
            self.fields.pop('backend')

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        # if editor maps groups user add viewer maps groups group to the user saved
        if commit:
            if self.cleaned_data['password1']:
                user.set_password(self.cleaned_data['password1'])
            user.save()

            # for save groups
            if 'groups' not in self.cleaned_data:
                self.cleaned_data['groups'] = self.request.user.groups.all()
            else:
                if self.cleaned_data['groups']:
                    self.cleaned_data['groups'] = self.cleaned_data['groups']
                else:
                    self.cleaned_data['groups'] = []

            if 'user_groups_editor' in self.cleaned_data and self.cleaned_data[
                    'user_groups_editor']:
                if self.cleaned_data['groups']:
                    self.cleaned_data['groups'] |= self.cleaned_data[
                        'user_groups_editor']
                else:
                    self.cleaned_data['groups'] = self.cleaned_data[
                        'user_groups_editor']

            if 'user_groups_viewer' in self.cleaned_data and self.cleaned_data[
                    'user_groups_viewer']:
                if self.cleaned_data['groups']:
                    self.cleaned_data['groups'] |= self.cleaned_data[
                        'user_groups_viewer']
                else:
                    self.cleaned_data['groups'] = self.cleaned_data[
                        'user_groups_viewer']

            # if is_superuser or is_staff are set, remove groups
            if ('is_superuser' in self.cleaned_data or 'is_staff' in self.cleaned_data) and \
                    (('is_superuser' in self.cleaned_data and self.cleaned_data['is_superuser']) or
                     ('is_staff' in self.cleaned_data and self.cleaned_data['is_staff'])):
                self.cleaned_data['groups'] = []
                self.cleaned_data['user_groups_editor'] = []
                self.cleaned_data['user_groups_viewer'] = []

            self.save_m2m()

            if hasattr(user, 'userdata'):
                if 'department' in self.cleaned_data:
                    user.userdata.department = self.cleaned_data['department']
                if self.cleaned_data['avatar']:
                    user.userdata.avatar = self.cleaned_data['avatar']
                else:
                    user.userdata.avatar = None
                user.userdata.save()
            else:
                Userdata(user=user,
                         department=self.cleaned_data['department'],
                         avatar=self.cleaned_data['avatar']).save()

            # add backend
            if 'backend' in self.cleaned_data:
                if hasattr(user, 'userbackend'):
                    user.userbackend.backend = self.cleaned_data['backend']
                    user.userbackend.save()
                else:
                    Userbackend(user=user,
                                backend=self.cleaned_data['backend']).save()
            elif not hasattr(user, 'userbackend'):
                Userbackend(user=user, backend=USER_BACKEND_DEFAULT).save()

            # add add_group permissions to editor1
            add_group = Permission.objects.get(
                codename='add_group',
                content_type=ContentType.objects.get_for_model(AuthGroup))
            if userHasGroups(user, [G3W_EDITOR1]):
                user.user_permissions.add(add_group)
            else:
                user.user_permissions.remove(add_group)

        return user

    def clean_groups(self):
        """
        Check for roles(groups) user can't be editor level 1 and 2 at same time.
        :return: cleaned_data modified
        """

        groups = self.cleaned_data['groups']

        if len(
                set(groups).intersection(
                    set(
                        AuthGroup.objects.filter(
                            name__in=[G3W_EDITOR1, G3W_EDITOR2])))) == 2:
            raise ValidationError(_(
                'User can\'t be Editor level 1 and at same time Editor level 2'
            ),
                                  code='groups_invalid')

        return groups

    def clean_user_groups_editor(self):
        """
        Check only Editor level 2 users can belong to user groups editor.
        :return: cleaned_data
        """
        user_groups_editor = self.cleaned_data['user_groups_editor']

        if user_groups_editor and 'groups' in self.cleaned_data and len(
                set(self.cleaned_data['groups']).intersection(
                    set(AuthGroup.objects.filter(
                        name__in=[G3W_EDITOR2])))) == 0:
            raise ValidationError(_(
                'User can\'t belong a **editor groups** if he isn\'t a Editor level 2'
            ),
                                  code='user_groups_editor_invalid')

        return user_groups_editor

    def clean_user_groups_viewer(self):
        """
        Check only Viewer level 1 users can belong to user groups editor.
        :return: cleaned_data
        """
        user_groups_viewer = self.cleaned_data['user_groups_viewer']

        if user_groups_viewer and 'groups' in self.cleaned_data and len(
                set(self.cleaned_data['groups']).intersection(
                    set(AuthGroup.objects.filter(
                        name__in=[G3W_VIEWER1])))) == 0:
            raise ValidationError(_(
                'User can\'t belong a **viewer groups** if he isn\'t a Viewer level 1'
            ),
                                  code='user_groups_editor_invalid')

        return user_groups_viewer

    def clean_avatar(self):
        """
        Check if upalod file is a valid image by pillow
        :return: File object Cleaned data
        """
        avatar = self.cleaned_data['avatar']
        if avatar is None:
            return avatar

        try:
            image = Image.open(avatar)
            image.verify()
        except Exception:
            raise ValidationError(_('Avatar is no a valid image'),
                                  code='image_invalid')
        return avatar

    class Meta(UserCreationForm.Meta):
        fields = ('first_name', 'last_name', 'email', 'username', 'password1',
                  'password2', 'is_superuser', 'is_staff', 'groups',
                  'department', 'avatar', 'user_groups_editor',
                  'user_groups_viewer')

        widgets = {
            #'groups': G3WM2MSingleSelect
        }
Ejemplo n.º 6
0
class WorkupForm(ModelForm):

    temperature_units = fields.ChoiceField(label='',
                                           widget=RadioSelect,
                                           choices=[(
                                               'C',
                                               'C',
                                           ), ('F', 'F')],
                                           initial='C',
                                           required=False)

    weight_units = fields.ChoiceField(label='',
                                      widget=RadioSelect,
                                      choices=[('kg', 'kg'), ('lbs', 'lbs')],
                                      required=False)

    height_units = fields.ChoiceField(label='',
                                      widget=RadioSelect,
                                      choices=[('cm', 'cm'), ('in', 'in')],
                                      required=False)

    class Meta(object):
        model = models.Workup
        exclude = [
            'patient', 'author', 'signer', 'author_type', 'signed_date',
            'referral_location', 'referral_type'
        ]

    # limit the options for the attending, other_volunteer field by
    # checking the signs charts permission.
    can_sign_perm_codename = 'sign_Workup'
    attending = ModelChoiceField(
        required=False,
        queryset=get_user_model().objects.filter(
            groups__in=Group.objects.filter(
                permissions__codename=can_sign_perm_codename)).distinct())

    other_volunteer = ModelMultipleChoiceField(
        required=False, queryset=get_user_model().objects.all())

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

        self.helper = FormHelper()
        self.helper.form_method = 'post'

        self.helper.layout = Layout(
            Row(HTML('<h3>Clinical Team</h3>'),
                Div('attending', css_class='col-sm-6'),
                Div('other_volunteer', css_class='col-sm-6'),
                Div('clinic_day', css_class='col-sm-12')),
            Row(
                HTML('<h3>History</h3>'),
                Div('chief_complaint', css_class='col-sm-6'),
                Div('diagnosis', css_class='col-sm-6'),
                Div(InlineCheckboxes('diagnosis_categories'),
                    css_class='col-sm-12'), Div('HPI', css_class='col-xs-12'),
                Div('PMH_PSH', css_class='col-xs-12'),
                Div('fam_hx', css_class='col-md-6'),
                Div('soc_hx', css_class='col-md-6'),
                Div('meds', css_class='col-md-6'),
                Div('allergies', css_class='col-md-6'),
                Div('ros', css_class='col-xs-12')),
            Row(
                HTML('<h3>Physical Exam</h3>'), HTML('<h4>Vital Signs</h4>'),
                Div(AppendedText('bp_sys', 'mmHg'),
                    css_class='col-md-3 col-sm-3 col-xs-6'),
                Div(AppendedText('bp_dia', 'mmHg'),
                    css_class='col-md-3 col-sm-3 col-xs-6'),
                Div(AppendedText('hr', 'bpm'),
                    css_class='col-md-3 col-sm-3 col-xs-6'),
                Div(AppendedText('rr', '/min'),
                    css_class='col-md-3 col-sm-3 col-xs-6')),
            Row(
                Div(AppendedRadios('t', 'temperature_units'),
                    css_class='col-md-3 col-sm-3 col-xs-6'),
                Div(AppendedRadios('weight', 'weight_units'),
                    css_class='col-md-3 col-sm-4 col-xs-6'),
                Div(AppendedRadios('height', 'height_units'),
                    css_class='col-md-3 col-sm-4 col-xs-6'),
                Div('pe', css_class='col-xs-12')),
            Row(
                HTML('<h3>Assessment, Plan, & Orders</h3>'),
                Div('A_and_P', css_class='col-xs-12'),
                Div('rx', css_class='col-md-4'),
                Div('labs_ordered_internal', css_class='col-md-4'),
                Div('labs_ordered_external', css_class='col-md-4'),
                Div(
                    HTML('<h4>Medication Voucher</h4>'),
                    'got_voucher',
                    PrependedText('voucher_amount', '$'),
                    PrependedText('patient_pays', '$'),
                    css_class='col-xs-6',
                ),
                Div(HTML('<h4>Imaging Voucher</h4>'),
                    'got_imaging_voucher',
                    PrependedText('imaging_voucher_amount', '$'),
                    PrependedText('patient_pays_imaging', '$'),
                    css_class='col-xs-6')),
            Submit('submit', 'Save', css_class='btn btn-success'))

        self.fields['ros'].widget.attrs['rows'] = 15
        self.fields['pe'].widget.attrs['rows'] = 14

        if not settings.OSLER_DISPLAY_DIAGNOSIS:
            # delete diagnosis
            self.helper.layout[1].pop(2)
            # delete diagnosis category
            self.helper.layout[1].pop(2)

        if not settings.OSLER_DISPLAY_VOUCHERS:
            # delete medication voucher
            self.helper.layout[4].pop(5)
            # delete imaging voucher
            self.helper.layout[4].pop(5)

    def clean(self):
        """Use form's clean hook to verify that fields in Workup are
        consistent with one another (e.g. if pt recieved a voucher, amount is
        given)."""

        cleaned_data = super(WorkupForm, self).clean()

        # we allow specification of units when the measurement is not given
        # because you cannot uncheck radios and the converter methods accept
        # Nones.
        form_required_if(self, 't', ['temperature_units'])
        form_required_if(self, 'height', ['height_units'])
        form_required_if(self, 'weight', ['weight_units'])

        form_required_if(self, 'got_voucher',
                         ['voucher_amount', 'patient_pays'])
        form_required_if(self, 'got_imaging_voucher',
                         ['imaging_voucher_amount', 'patient_pays_imaging'])

        attending = cleaned_data.get('attending')
        if attending and attending in cleaned_data.get('other_volunteer'):
            self.add_error(
                'other_volunteer',
                'Attending physician must be different from other volunteers.')

        if 't' in cleaned_data and cleaned_data.get('t') is not None:
            if cleaned_data.get('temperature_units') == 'F':
                c = Decimal(fahrenheit2centigrade(
                    cleaned_data.get('t'))).quantize(Decimal('.1'),
                                                     rounding=ROUND_HALF_UP)
                cleaned_data['t'] = c

        if 'weight' in cleaned_data and cleaned_data.get('weight') is not None:
            if cleaned_data.get('weight_units') == 'lbs':
                kgs = Decimal(pounds2kilos(
                    cleaned_data.get('weight'))).quantize(
                        Decimal('.1'), rounding=ROUND_HALF_UP)
                cleaned_data['weight'] = kgs

        if 'height' in cleaned_data and cleaned_data.get('height') is not None:
            if cleaned_data.get('height_units') == 'in':
                cm = int(inches2cm(cleaned_data.get('height')))
                cleaned_data['height'] = cm

        for field in ['ros', 'pe'] + settings.OSLER_WORKUP_COPY_FORWARD_FIELDS:
            cleaned_data[field] = cleaned_data.get(field).strip()
            if "UPDATE" in cleaned_data.get(field):
                self.add_error(
                    field,
                    _("Please delete the heading and update contents as necessary"
                      ))

        form_require_together(self, ['bp_sys', 'bp_dia'])
        if cleaned_data.get('bp_sys') and cleaned_data.get('bp_dia'):
            if cleaned_data.get('bp_sys') <= cleaned_data.get('bp_dia'):
                for field in ['bp_sys', 'bp_dia']:
                    self.add_error(
                        field,
                        'Systolic blood pressure must be strictly greater '
                        'than diastolic blood pressure.')
Ejemplo n.º 7
0
class AddSubjectToteacherForm(Form):
    teacher = IntegerField(widget=HiddenInput(), required=True)
    courses = ModelMultipleChoiceField(widget=CourseWidget, queryset=Course.objects.all(), required=False, label='Выберете дисциплины')
 class SomeForm(Form):
     field = ModelMultipleChoiceField(ChoiceModel.objects.all())
Ejemplo n.º 9
0
class FlashcardCreateForm(Form):
    text_prompt = CharField(label='Text Prompt Link', widget=Textarea)
    answer = CharField(label='Answer', widget=Textarea)
    decks = ModelMultipleChoiceField(queryset=Deck.objects.all())
Ejemplo n.º 10
0
class CustomerAdminForm(ModelForm):
    owners = ModelMultipleChoiceField(
        User.objects.all().order_by('full_name'),
        required=False,
        widget=FilteredSelectMultiple(verbose_name=_('Owners'), is_stacked=False),
    )
    support_users = ModelMultipleChoiceField(
        User.objects.all().order_by('full_name'),
        required=False,
        widget=FilteredSelectMultiple(
            verbose_name=_('Support users'), is_stacked=False
        ),
    )

    def __init__(self, *args, **kwargs):
        super(CustomerAdminForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.owners = self.instance.get_owners()
            self.support_users = self.instance.get_support_users()
            self.fields['owners'].initial = self.owners
            self.fields['support_users'].initial = self.support_users
        else:
            self.owners = User.objects.none()
            self.support_users = User.objects.none()
        self.fields['agreement_number'].initial = models.get_next_agreement_number()

        textarea_attrs = {'cols': '40', 'rows': '4'}
        self.fields['contact_details'].widget.attrs = textarea_attrs
        self.fields['access_subnets'].widget.attrs = textarea_attrs
        type_choices = ['']
        type_choices.extend(settings.WALDUR_CORE['COMPANY_TYPES'])
        self.fields['type'] = ChoiceField(
            required=False, choices=[(t, t) for t in type_choices]
        )

    def save(self, commit=True):
        customer = super(CustomerAdminForm, self).save(commit=False)

        if not customer.pk:
            customer.save()

        self.populate_users('owners', customer, models.CustomerRole.OWNER)
        self.populate_users('support_users', customer, models.CustomerRole.SUPPORT)

        return customer

    def populate_users(self, field_name, customer, role):
        field = getattr(self, field_name)
        new_users = self.cleaned_data[field_name]

        removed_users = field.exclude(pk__in=new_users)
        for user in removed_users:
            customer.remove_user(user, role, self.request.user)

        added_users = new_users.exclude(pk__in=field)
        for user in added_users:
            # User role within customer must be unique.
            if not customer.has_user(user):
                customer.add_user(user, role, self.request.user)

        self.save_m2m()

    def clean(self):
        cleaned_data = super(CustomerAdminForm, self).clean()
        owners = self.cleaned_data['owners']
        support_users = self.cleaned_data['support_users']
        invalid_users = set(owners) & set(support_users)
        if invalid_users:
            invalid_users_list = ', '.join(map(str, invalid_users))
            raise ValidationError(
                _(
                    'User role within organization must be unique. '
                    'Role assignment of The following users is invalid: %s.'
                )
                % invalid_users_list
            )
        return cleaned_data

    def clean_accounting_start_date(self):
        accounting_start_date = self.cleaned_data['accounting_start_date']
        if (
            'accounting_start_date' in self.changed_data
            and accounting_start_date < timezone.now()
        ):
            # If accounting_start_date < timezone.now(), we change accounting_start_date
            # but not raise an exception, because accounting_start_date default value is
            # timezone.now(), but init time of form and submit time of form are always diff.
            # And user will get an exception always if set default value.
            return timezone.now()

        return accounting_start_date
Ejemplo n.º 11
0
class ProjectAdminForm(ModelForm):
    admins = ModelMultipleChoiceField(
        User.objects.all().order_by('full_name'),
        required=False,
        widget=FilteredSelectMultiple(verbose_name=_('Admins'), is_stacked=False),
    )
    managers = ModelMultipleChoiceField(
        User.objects.all().order_by('full_name'),
        required=False,
        widget=FilteredSelectMultiple(verbose_name=_('Managers'), is_stacked=False),
    )
    support_users = ModelMultipleChoiceField(
        User.objects.all().order_by('full_name'),
        required=False,
        widget=FilteredSelectMultiple(
            verbose_name=_('Support users'), is_stacked=False
        ),
    )

    def __init__(self, *args, **kwargs):
        super(ProjectAdminForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.admins = self.instance.get_users(models.ProjectRole.ADMINISTRATOR)
            self.managers = self.instance.get_users(models.ProjectRole.MANAGER)
            self.support_users = self.instance.get_users(models.ProjectRole.SUPPORT)
            self.fields['admins'].initial = self.admins
            self.fields['managers'].initial = self.managers
            self.fields['support_users'].initial = self.support_users
        else:
            for field_name in ('admins', 'managers', 'support_users'):
                setattr(self, field_name, User.objects.none())

    def clean(self):
        cleaned_data = super(ProjectAdminForm, self).clean()
        admins = self.cleaned_data['admins']
        managers = self.cleaned_data['managers']
        support_users = self.cleaned_data['support_users']
        for xs, ys in itertools.combinations(
            [set(admins), set(managers), set(support_users)], 2
        ):
            invalid_users = xs & ys
            if invalid_users:
                invalid_users_list = ', '.join(map(str, invalid_users))
                raise ValidationError(
                    _(
                        'User role within project must be unique. '
                        'Role assignment of The following users is invalid: %s.'
                    )
                    % invalid_users_list
                )
        return cleaned_data

    def save(self, commit=True):
        project = super(ProjectAdminForm, self).save(commit=False)

        if not project.pk:
            project.save()

        self.populate_users('admins', project, models.ProjectRole.ADMINISTRATOR)
        self.populate_users('managers', project, models.ProjectRole.MANAGER)
        self.populate_users('support_users', project, models.ProjectRole.SUPPORT)

        return project

    def populate_users(self, field_name, project, role):
        field = getattr(self, field_name)
        new_users = self.cleaned_data[field_name]

        removed_users = field.exclude(pk__in=new_users)
        for user in removed_users:
            project.remove_user(user, role, self.request.user)

        added_users = new_users.exclude(pk__in=field)
        for user in added_users:
            # User role within project must be unique.
            if not project.has_user(user):
                project.add_user(user, role, self.request.user)
        self.save_m2m()
Ejemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     super(InvoiceForm, self).__init__(*args, **kwargs)
     self.empty_permitted = False
     self.fields['date_due'] = DateField(widget=SelectDateWidget(
         empty_label=None,
         months=self.Meta.model.MONTHS,
         attrs={'class': 'form-control invoice_date_widget'}))
     self.fields['related_ticket_references'] = CharField(max_length=255)
     self.fields['invoice_items'] = ModelMultipleChoiceField(
         queryset=InvoiceItem.objects.all())
     self.fields['issued_by'] = ModelChoiceField(
         queryset=Account.objects.all())
     self.fields['paid_amount'] = DecimalField(max_digits=9,
                                               decimal_places=2)
     # # SET WIDGET ATTRIBUTES
     self.fields['related_ticket_references'].widget = TextInput(
         attrs={'class': 'form-control'})
     self.fields['related_ticket_references'].help_text = _(
         'Ticket number(s) related to this invoice')
     self.fields['invoice_comments'].widget = Textarea(
         attrs={'class': 'form-control'})
     self.fields['invoice_comments'].help_text = _(
         'Any additional comments about this invoice')
     self.fields['invoice_items'].widget = SelectMultiple(
         attrs={'class': 'form-control'})
     self.fields['invoice_items'].help_text = _(
         'Select items, then quantities below')
     self.fields['paid_amount'].widget = self.MyNumberInput(
         attrs={
             'class': 'form-control',
             'min': '0.00',
             'step': '0.01',
             'disabled': True
         })
     self.fields['paid_amount'].help_text = _(
         'Enter partial payment amount')
     self.fields['issued_by'].widget = Select(
         attrs={'class': 'form-control'})
     self.fields['issued_by'].help_text = _(
         'Select a business to issue from')
     self.fields['discount_rate'].widget = Select(
         attrs={'class': 'form-control'},
         choices=self.Meta.model.DISCOUNT_RATE)
     self.fields['tax'].widget = Select(attrs={'class': 'form-control'},
                                        choices=self.Meta.model.TAX)
     self.fields['invoice_status'].widget = Select(
         attrs={'class': 'form-control'},
         choices=self.Meta.model.INVOICE_STATUS)
     self.fields['invoice_number'] = CharField(widget=HiddenInput(
     ))  # to pass ID to view when updating existing inst.
     self.fields['invoice_emailed'].widget = CheckboxInput(
         attrs={'class': 'form-control'})
     self.fields['receipt_emailed'].widget = CheckboxInput(
         attrs={'class': 'form-control'})
     self.fields['recurring'] = ChoiceField(choices=Invoice.RECURRING)
     self.fields['recurring'].widget = Select(
         attrs={'class': 'form-control'}, choices=Invoice.RECURRING)
     self.fields['recurring'].help_text = _(
         'Is this to be a recurring invoice?')
     # # extra form fields (not included model)
     self.fields['form_hidden_field_post_action'] = CharField(
         widget=HiddenInput())  # for view's routing of POST request
     self.fields['client'] = CharField(
         widget=HiddenInput())  # to pass client if a new invoice
     # set required to False for all fields, to avoid validation issues when updating.
     for k, v in self.fields.items():
         self.fields[k].required = False
Ejemplo n.º 13
0
Archivo: forms.py Proyecto: g10f/sso
class OrganisationCountryForm(BaseForm):
    email_value = EmailFieldLower(required=True, label=_("Email address"))
    country_groups = ModelMultipleChoiceField(
        queryset=CountryGroup.objects.all(),
        required=False,
        widget=bootstrap.CheckboxSelectMultiple(),
        label=_("Country Groups"))

    class Meta:
        model = OrganisationCountry

        fields = ('association', 'homepage', 'country_groups', 'country',
                  'is_active')
        widgets = {
            'homepage': bootstrap.TextInput(attrs={'size': 50}),
            'association': bootstrap.Select(),
            'country': bootstrap.Select2(),
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')  # remove custom user keyword
        super().__init__(*args, **kwargs)
        if self.instance.email:
            self.fields['email_value'].initial = force_str(self.instance.email)
        else:
            self.fields['email_value'].initial = SSO_ORGANISATION_EMAIL_DOMAIN
        if self.instance.pk is not None and self.instance.country:
            # readonly field for the update form
            self.fields['country_text'] = bootstrap.ReadOnlyField(
                initial=force_str(self.instance.country), label=_("Country"))
            self.fields['association_text'] = bootstrap.ReadOnlyField(
                initial=force_str(self.instance.association),
                label=_("Association"))
            del self.fields['association']
            del self.fields['country']
        else:
            self.fields[
                'association'].queryset = self.user.get_administrable_associations(
                )

    def clean_email_value(self):
        """
        the new email address must be ending with SSO_ORGANISATION_EMAIL_DOMAIN
        """
        email_value = self.cleaned_data['email_value']
        if SSO_ORGANISATION_EMAIL_DOMAIN and email_value[
                -len(SSO_ORGANISATION_EMAIL_DOMAIN
                     ):] != SSO_ORGANISATION_EMAIL_DOMAIN:
            msg = _(
                'The email address of the center must be ending with %(domain)s'
            ) % {
                'domain': SSO_ORGANISATION_EMAIL_DOMAIN
            }
            raise ValidationError(msg)

        if Email.objects.filter(email=email_value).exclude(
                organisationcountry=self.instance).exists():
            msg = _('The email address already exists')
            raise ValidationError(msg)

        return email_value

    def save(self, commit=True):
        instance = super().save(commit)
        if 'email_value' in self.changed_data:
            if self.instance.email:
                self.instance.email.email = self.cleaned_data['email_value']
                self.instance.email.save()
            else:
                # create email object
                email = Email(email_type=COUNTRY_EMAIL_TYPE,
                              permission=PERM_DWB,
                              email=self.cleaned_data['email_value'])
                email.save()
                instance.email = email
                instance.save()

        return instance
Ejemplo n.º 14
0
class WorkupForm(ModelForm):

    temperature_units = fields.ChoiceField(label='',
                                           widget=RadioSelect,
                                           choices=[('C', 'C'), ('F', 'F')],
                                           required=False)

    weight_units = fields.ChoiceField(label='',
                                      widget=RadioSelect,
                                      choices=[('kg', 'kg'), ('lbs', 'lbs')],
                                      required=False)

    height_units = fields.ChoiceField(label='',
                                      widget=RadioSelect,
                                      choices=[('cm', 'cm'), ('in', 'in')],
                                      required=False)

    class Meta:
        model = models.Workup
        exclude = [
            'patient', 'clinic_day', 'author', 'signer', 'author_type',
            'signed_date'
        ]
        widgets = {
            'referral_location': CheckboxSelectMultiple,
            'referral_type': CheckboxSelectMultiple
        }

    # limit the options for the attending, other_volunteer field to
    # Providers with ProviderType with signs_charts=True, False
    # (includes coordinators and volunteers)
    attending = ModelChoiceField(
        required=False,
        queryset=Provider.objects.filter(
            clinical_roles__in=ProviderType.objects.filter(
                signs_charts=True)).order_by("last_name"))

    other_volunteer = ModelMultipleChoiceField(
        required=False,
        queryset=Provider.objects.filter(
            clinical_roles__in=ProviderType.objects.filter(
                signs_charts=False)).distinct().order_by("last_name"),
    )

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

        self.helper = FormHelper()
        self.helper.form_method = 'post'

        self.helper.layout = Layout(
            Row(HTML('<h3>Clinical Team</h3>'),
                Div('attending', css_class='col-sm-6'),
                Div('other_volunteer', css_class='col-sm-6')),
            Row(
                HTML('<h3>History</h3>'),
                Div('chief_complaint', css_class='col-sm-6'),
                Div('diagnosis', css_class='col-sm-6'),
                Div(InlineCheckboxes('diagnosis_categories'),
                    css_class='col-xs-12'), Div('HPI', css_class='col-xs-12'),
                Div('PMH_PSH', css_class='col-xs-12'),
                Div('fam_hx', css_class='col-md-6'),
                Div('soc_hx', css_class='col-md-6'),
                Div('meds', css_class='col-md-6'),
                Div('allergies', css_class='col-md-6'),
                Div('ros', css_class='col-xs-12')),
            Row(
                HTML('<h3>Physical Exam</h3>'), HTML('<h4>Vital Signs</h4>'),
                Div(AppendedText('hr', 'bpm'),
                    css_class='col-md-4 col-sm-6 col-xs-12'),
                Div(AppendedText('rr', '/min'),
                    css_class='col-md-4 col-sm-6 col-xs-12'),
                Div(AppendedText('t',
                                 unit_selector_html('temperature',
                                                    ['C', 'F'])),
                    css_class='col-md-4 col-sm-6 col-xs-12'),
                Div(AppendedText('bp_sys', 'mmHg'),
                    css_class='col-md-4 col-sm-3 col-xs-6'),
                Div(AppendedText('bp_dia', 'mmHg'),
                    css_class='col-md-4 col-sm-3 col-xs-6'),
                Div(AppendedText('height',
                                 unit_selector_html('height', ['in', 'cm'])),
                    css_class='col-md-4 col-sm-6 col-xs-12'),
                Div(AppendedText('weight',
                                 unit_selector_html('weight', ['kg', 'lbs'])),
                    css_class='col-md-4 col-sm-6 col-xs-12'),
                Div('pe', css_class='col-xs-12')),
            Row(
                HTML('<h3>Assessment, Plan, & Orders</h3>'),
                Div('A_and_P', css_class='col-xs-12'),
                Div('rx', css_class='col-md-4'),
                Div('labs_ordered_internal', css_class='col-md-4'),
                Div('labs_ordered_quest', css_class='col-md-4'),
                Div(
                    HTML('<h4>Medication Voucher</h4>'),
                    'got_voucher',
                    PrependedText('voucher_amount', '$'),
                    PrependedText('patient_pays', '$'),
                    css_class='col-xs-6',
                ),
                Div(HTML('<h4>Imaging Voucher</h4>'),
                    'got_imaging_voucher',
                    PrependedText('imaging_voucher_amount', '$'),
                    PrependedText('patient_pays_imaging', '$'),
                    css_class='col-xs-6')),
            Row(
                HTML('<h3>Referral & Discharge</h3>'),
                Div('will_return', css_class='col-xs-12'),
                Div(Field('referral_location',
                          style="background: #FAFAFA; padding: 10px;"),
                    css_class='col-sm-6'),
                Div(Field('referral_type',
                          style="background: #FAFAFA; padding: 10px;"),
                    css_class='col-sm-6')),
            Submit('submit', 'Save', css_class='btn btn-success'))

    def clean(self):
        '''Use form's clean hook to verify that fields in Workup are
        consistent with one another (e.g. if pt recieved a voucher, amount is
        given).'''

        cleaned_data = super(WorkupForm, self).clean()

        # we allow specification of units when the measurement is not given
        # because you cannot uncheck radios and the converter methods accept
        # Nones.
        form_required_if(self, 't', ['temperature_units'])
        form_required_if(self, 'height', ['height_units'])
        form_required_if(self, 'weight', ['weight_units'])

        form_required_if(self, 'got_voucher',
                         ['voucher_amount', 'patient_pays'])
        form_required_if(self, 'got_imaging_voucher',
                         ['imaging_voucher_amount', 'patient_pays_imaging'])

        if cleaned_data.get('temperature_units') == 'F':
            c = fahrenheit2centigrade(cleaned_data.get('t'))
            cleaned_data['t'] = c

        if cleaned_data.get('weight_units') == 'lbs':
            kgs = pounds2kilos(cleaned_data.get('weight'))
            cleaned_data['weight'] = kgs

        if cleaned_data.get('height_units') == 'in':
            cm = inches2cm(cleaned_data.get('height'))
            cleaned_data['height'] = cm

        form_require_together(self, ['bp_sys', 'bp_dia'])
        if cleaned_data.get('bp_sys') and cleaned_data.get('bp_dia'):
            if cleaned_data.get('bp_sys') <= cleaned_data.get('bp_dia'):
                for field in ['bp_sys', 'bp_dia']:
                    self.add_error(
                        field,
                        'Systolic blood pressure must be strictly greater '
                        'than diastolic blood pressure.')
Ejemplo n.º 15
0
class UserProfileAdminForm(forms.ModelForm):
    allowed_archival_units = ModelMultipleChoiceField(queryset=ArchivalUnit.objects.filter(level='S'),
                                                      required=False)
Ejemplo n.º 16
0
class _RelationsCreateForm(CremeForm):
    relations = core_fields.MultiRelationEntityField(
        label=_('Relationships'),
        required=False,
        autocomplete=True,
    )
    semifixed_rtypes = ModelMultipleChoiceField(
        label=_('Semi-fixed types of relationship'),
        queryset=SemiFixedRelationType.objects.none(),
        required=False,
    )

    error_messages = {
        'duplicates':
        _('There are duplicates: %(duplicates)s'),
        'link_themselves':
        _('An entity can not be linked to itself : %(entities)s'),
        'empty':
        _('You must give one relationship at least.'),
        'missing_property_single':
        _('«%(subject)s» must have the property «%(property)s» '
          'in order to use the relationship «%(predicate)s»'),
        'missing_property_multi':
        _('«%(subject)s» must have a property in «%(properties)s» '
          'in order to use the relationship «%(predicate)s»'),
    }

    def __init__(self,
                 subjects,
                 content_type,
                 relations_types=None,
                 *args,
                 **kwargs):
        """Constructor.
        @param subjects: CremeEntity instances that will be the subjects of Relations.
        @param content_type: Type of the subjects.
        @param relations_types: Sequence of RelationTypes ids to narrow to these types ;
               A empty sequence means all types compatible with the parameter 'content_type'.
        """
        super().__init__(*args, **kwargs)
        self.subjects = subjects
        self.subjects_ids = subjects_ids = frozenset(s.id for s in subjects)

        fields = self.fields
        # TODO: improve queries ??
        user = self.user
        entities = [
            sfrt.object_entity
            for sfrt in SemiFixedRelationType.objects.exclude(
                object_entity__in=subjects_ids).select_related('object_entity')
        ]
        sfrt_queryset = SemiFixedRelationType.objects.filter(
            object_entity__in=filter(user.has_perm_to_link, entities), )

        if not relations_types:
            relations_types = RelationType.objects.compatible(content_type)
            sfrt_queryset = sfrt_queryset.filter(
                Q(relation_type__subject_ctypes=content_type)
                | Q(relation_type__subject_ctypes__isnull=True))
        else:
            sfrt_queryset = sfrt_queryset.filter(
                relation_type__in=relations_types)

        fields['semifixed_rtypes'].queryset = sfrt_queryset

        # TODO: add a qfilter to exclude the subjects from possible objects
        relations_field = fields['relations']
        relations_field.allowed_rtypes = relations_types
        relations_field.initial = [(relations_field.allowed_rtypes.all()[0],
                                    None)]

    def _check_duplicates(self, relations, user):
        future_relations = set()
        duplicates = []

        for rtype, entity in relations:
            r_id = f'{rtype.id}#{entity.id}'

            if r_id in future_relations:
                duplicates.append((rtype, entity))
            else:
                future_relations.add(r_id)

        if duplicates:
            raise ValidationError(
                self.error_messages['duplicates'],
                params={
                    'duplicates':
                    ', '.join(f'({rtype}, {e.allowed_str(user)})'
                              for rtype, e in duplicates),
                },
                code='duplicates',
            )

    # TODO: indicates all subjects which miss properties ?
    # TODO: filter & display these invalid subjects (like non editable subjects)
    def _check_properties(self, rtypes):
        subjects = self.subjects
        need_validation = False
        ptypes_contraints = OrderedDict()

        for rtype in rtypes:
            if rtype.id not in ptypes_contraints:
                properties = dict(
                    rtype.subject_properties.values_list('id', 'text'))
                ptypes_contraints[rtype.id] = (rtype, properties)

                if properties:
                    need_validation = True

        if not need_validation:
            return

        CremeEntity.populate_properties(subjects)

        for subject in subjects:
            for rtype, needed_properties in ptypes_contraints.values():
                if not needed_properties:
                    continue

                subject_prop_ids = {
                    p.type_id
                    for p in subject.get_properties()
                }

                if any(ptype_id not in subject_prop_ids
                       for ptype_id in needed_properties.keys()):
                    if len(needed_properties) == 1:
                        raise ValidationError(
                            self.error_messages['missing_property_single'],
                            params={
                                'subject': subject,
                                'property':
                                next(iter(needed_properties.values())),
                                'predicate': rtype.predicate,
                            },
                            code='missing_property_single',
                        )
                    else:
                        raise ValidationError(
                            self.error_messages['missing_property_multi'],
                            params={
                                'subject':
                                subject,
                                'properties':
                                '/'.join(
                                    sorted(map(str,
                                               needed_properties.values()))),
                                'predicate':
                                rtype.predicate,
                            },
                            code='missing_property_multi',
                        )

    def _check_loops(self, relations):
        subjects_ids = self.subjects_ids
        bad_objects = [
            str(entity) for rtype, entity in relations
            if entity.id in subjects_ids
        ]

        if bad_objects:
            raise ValidationError(
                self.error_messages['link_themselves'],
                params={'entities': ', '.join(bad_objects)},
                code='link_themselves',
            )

    def clean_relations(self):
        relations = self.cleaned_data['relations']

        self._check_duplicates(relations, self.user)
        self._check_loops(relations)
        self._check_properties([rtype for rtype, e_ in relations])

        return relations

    def clean_semifixed_rtypes(self):
        sf_rtypes = self.cleaned_data['semifixed_rtypes']
        self._check_properties(
            [sf_rtype.relation_type for sf_rtype in sf_rtypes])

        return sf_rtypes

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

        if not self._errors:
            relations_desc = cdata['relations']
            # TODO: improve queries ??
            relations_desc.extend((sfrt.relation_type, sfrt.object_entity)
                                  for sfrt in cdata['semifixed_rtypes'])

            if not relations_desc:
                raise ValidationError(self.error_messages['empty'],
                                      code='empty')

            self._check_duplicates(relations_desc, self.user)

            self.relations_desc = relations_desc

        return cdata

    def save(self):
        user = self.user

        Relation.objects.safe_multi_save(
            Relation(
                user=user,
                subject_entity=subject,
                type=rtype,
                object_entity=object_entity,
            ) for subject in self.subjects
            for rtype, object_entity in self.relations_desc)
Ejemplo n.º 17
0
class AirportForm(ModelForm):
    class Meta:
        model = Airport
        fields = FIELDS

    airlines = ModelMultipleChoiceField(required=False, queryset=Airline.objects.all())
Ejemplo n.º 18
0
class ContestTagForm(ModelForm):
    contests = ModelMultipleChoiceField(
        label=_('Included contests'),
        queryset=Contest.objects.all(),
        required=False,
        widget=HeavySelect2MultipleWidget(data_view='contest_select2', attrs={'style': 'width: 100%'}))
Ejemplo n.º 19
0
class BatchForm(ModelForm):
    csv_file = FileField(label='CSV File')

    # Allow a form to be submitted without an 'allotted_assignment_time'
    # field.  The default value for this field will be used instead.
    # See also the function clean_allotted_assignment_time().
    allotted_assignment_time = IntegerField(initial=Batch._meta.get_field(
        'allotted_assignment_time').get_default(),
                                            required=False)

    worker_permissions = ModelMultipleChoiceField(
        label='Worker Groups with access to this Batch',
        queryset=Group.objects.all(),
        required=False,
        widget=FilteredSelectMultiple('Worker Groups', False),
    )

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

        self.fields[
            'allotted_assignment_time'].label = 'Allotted assignment time (hours)'
        self.fields['allotted_assignment_time'].help_text = 'If a user abandons a Task, ' + \
            'this determines how long it takes until their assignment is deleted and ' + \
            'someone else can work on the Task.'
        self.fields['csv_file'].help_text = 'You can Drag-and-Drop a CSV file onto this ' + \
            'window, or use the "Choose File" button to browse for the file'
        self.fields['csv_file'].widget = CustomButtonFileWidget(
            attrs={
                'class': 'hidden',
                'data-parsley-errors-container': '#file-upload-error',
            })
        self.fields[
            'custom_permissions'].label = 'Restrict access to specific Groups of Workers '
        self.fields['project'].label = 'Project'
        self.fields['name'].label = 'Batch Name'

        self.fields['active'].help_text = 'Workers can only access a Batch if both the Batch ' + \
            'itself and the associated Project are Active.'

        if self.instance._state.adding and 'project' in self.initial:
            # We are adding a new Batch where the associated Project has been specified.
            # Per Django convention, the project ID is specified in the URL, e.g.:
            #   /admin/turkle/batch/add/?project=94

            # NOTE: The fields that are initialized here should match the fields copied
            #       over by the batch.copy_project_permissions() function.

            project = Project.objects.get(id=int(self.initial['project']))
            self.fields[
                'custom_permissions'].initial = project.custom_permissions
            self.fields['login_required'].initial = project.login_required

            # Pre-populate permissions using permissions from the associated Project
            initial_ids = [
                str(id)
                for id in get_groups_with_perms(project).values_list('id',
                                                                     flat=True)
            ]
        else:
            # Pre-populate permissions
            initial_ids = [
                str(id) for id in get_groups_with_perms(
                    self.instance).values_list('id', flat=True)
            ]
        self.fields['worker_permissions'].initial = initial_ids

        # csv_file field not required if changing existing Batch
        #
        # When changing a Batch, the BatchAdmin.get_fields()
        # function will cause the form to be rendered without
        # displaying an HTML form field for the csv_file field.  I was
        # running into strange behavior where Django would still try
        # to validate the csv_file form field, even though there was
        # no way for the user to provide a value for this field.  The
        # two lines below prevent this problem from occurring, by
        # making the csv_file field optional when changing
        # a Batch.
        if not self.instance._state.adding:
            self.fields['csv_file'].required = False
            self.fields['project'].widget = \
                ProjectNameReadOnlyWidget(self.instance.project)

    def clean(self):
        """Verify format of CSV file

        Verify that:
        - fieldnames in CSV file are identical to fieldnames in Project
        - number of fields in each row matches number of fields in CSV header
        """
        cleaned_data = super().clean()

        csv_file = cleaned_data.get("csv_file", False)
        project = cleaned_data.get("project")

        if not csv_file or not project:
            return

        validation_errors = []

        # django InMemoryUploadedFile returns bytes and we need strings
        rows = csv.reader(StringIO(csv_file.read().decode('utf-8')))
        header = next(rows)

        csv_fields = set(header)
        template_fields = set(project.fieldnames)
        if csv_fields != template_fields:
            template_but_not_csv = template_fields.difference(csv_fields)
            if template_but_not_csv:
                validation_errors.append(
                    ValidationError(
                        'The CSV file is missing fields that are in the HTML template. '
                        'These missing fields are: %s' %
                        ', '.join(template_but_not_csv)))

        expected_fields = len(header)
        for (i, row) in enumerate(rows):
            if len(row) != expected_fields:
                validation_errors.append(
                    ValidationError(
                        'The CSV file header has %d fields, but line %d has %d fields'
                        % (expected_fields, i + 2, len(row))))

        if validation_errors:
            raise ValidationError(validation_errors)

        # Rewind file, so it can be re-read
        csv_file.seek(0)

    def clean_allotted_assignment_time(self):
        """Clean 'allotted_assignment_time' form field

        - If the allotted_assignment_time field is not submitted as part
          of the form data (e.g. when interacting with this form via a
          script), use the default value.
        - If the allotted_assignment_time is an empty string (e.g. when
          submitting the form using a browser), raise a ValidationError
        """
        data = self.data.get('allotted_assignment_time')
        if data is None:
            return Batch._meta.get_field(
                'allotted_assignment_time').get_default()
        elif data.strip() == '':
            raise ValidationError('This field is required.')
        else:
            return data
Ejemplo n.º 20
0
class SearchForm(Form):
    tags = ModelMultipleChoiceField(queryset=Tag.objects,
                                    widget=CheckboxSelectMultiple)
    choices = (('Post', 'Search posts'), ('Question', 'Search questions'))
    search_page = ChoiceField(choices=choices, widget=RadioSelect)
Ejemplo n.º 21
0
class AirportForm(forms.ModelForm):
    class Meta:
        model = Airport
        fields = ['name', 'x', 'y', 'airlines']
        exclude = []
        widgets = None
        localized_fields = None
        labels = {}
        help_texts = {}
        error_messages = {}

    airlines = ModelMultipleChoiceField(required=False,
                                        queryset=Airline.objects.all())

    def __init__(self, *args, **kwargs):
        if kwargs.get('instance'):
            initial = kwargs.setdefault('initial', {})
            initial['airlines'] = [
                t.pk for t in kwargs['instance'].airlines.all()
            ]
        super(AirportForm, self).__init__(*args, **kwargs)

    def is_valid(self):
        return super(AirportForm, self).is_valid()

    def full_clean(self):
        return super(AirportForm, self).full_clean()

    def clean_name(self):
        name = self.cleaned_data.get("name", None)
        return name

    def clean_x(self):
        x = self.cleaned_data.get("x", None)
        return x

    def clean_y(self):
        y = self.cleaned_data.get("y", None)
        return y

    def clean(self):
        return super(AirportForm, self).clean()

    def validate_unique(self):
        return super(AirportForm, self).validate_unique()

    def save(self, commit=True):
        instance = super(AirportForm, self).save(commit)

        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m

        def save_m2m():
            old_save_m2m()
            # This is where we actually link the pizza with toppings
            instance.airlines.clear()
            instance.airlines.add(*self.cleaned_data['airlines'])

        self.save_m2m = save_m2m

        # Do we need to save all changes now?
        if commit:
            instance.save()
            self.save_m2m()

        return instance
Ejemplo n.º 22
0
class GameForm(ModelForm):
    class Meta:
        model = Game
        exclude = ['game_master', 'status']

    plugins = ModelMultipleChoiceField(queryset=Plugin.objects.all(), widget=CheckboxSelectMultiple, required=False)
Ejemplo n.º 23
0
class DefinitionForm(forms.ModelForm):
    word = forms.CharField(required=True,
                           label='শব্দ *',
                           max_length=100,
                           widget=TextInput(
                               attrs={
                                   'id': 'words',
                                   'class': 'form-group form-control',
                                   'placeholder': "এখানে শব্দটি লিখুন..."
                               }))
    define = forms.CharField(required=True,
                             label='শব্দের ব্যাখ্যা *',
                             widget=Textarea(
                                 attrs={
                                     'placeholder': 'শব্দের ব্যাখ্যা লিখুন...',
                                     'rows': '2',
                                     'id': 'def',
                                     'class': 'form-group form-control'
                                 }),
                             max_length=800)
    sentence_ex = forms.CharField(
        required=True,
        label='শব্দটি সম্বলিত একটি বাক্য *',
        widget=Textarea(
            attrs={
                'placeholder': 'এখানে বাক্যটি লিখুন...',
                'rows': '4',
                'id': 'ex',
                'class': 'form-group form-control'
            }),
        max_length=1000)
    tags = ModelMultipleChoiceField(
        queryset=Tag.objects.all(),
        label='ট্যাগসমূহ *',
        widget=Select2MultipleWidget(
            attrs={
                'id': 'tags',
                'class': 'form-group form-control mb-2',
                'placeholder': ''
            }))
    synonyms = ModelMultipleChoiceField(
        required=False,
        queryset=Word.objects.all(),
        label='সমার্থক শব্দ',
        widget=Select2MultipleWidget(
            attrs={
                'data-placeholder': 'সমার্থক শব্দ বাছাই করুন',
                'id': 'syn',
                'class': 'form-group form-control  mb-2'
            }))
    antonyms = ModelMultipleChoiceField(
        required=False,
        queryset=Word.objects.all(),
        label='বিপরীত শব্দ',
        widget=Select2TagWidget(
            attrs={
                'data-placeholder': 'বিপরীত শব্দ বাছাই করুন',
                'id': 'ant',
                'class': 'form-group form-control '
            }))

    class Meta:
        model = Definition
        fields = [
            'word', 'define', 'sentence_ex', 'tags', 'synonyms', 'antonyms'
        ]

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

    #
    def clean_word(self):
        w = self.cleaned_data['word']
        print(self.cleaned_data)
        restricted_names = [
            "শেখ", "হাসিনা", "লীগ", "মুজিব", "শেখ মুজিবুর রহমান", "বঙ্গবন্ধু",
            "জিয়া", "খালেদা"
        ]
        try:
            wo = Word.objects.get(word_name=w)
        except Word.DoesNotExist:
            for word in restricted_names:
                if word in w:
                    raise forms.ValidationError(
                        "অনুগ্রহ করে সঠিক শব্দটি লিখুন")
            isBang = True
            for c in w:
                if c != ' ':
                    try:
                        if detect(c) != 'bn':
                            isBang = False
                    except:
                        pass
            if isBang == False:
                raise forms.ValidationError("অনুগ্রহ করে বাংলা শব্দ লিখুন")
            u = self.request
            Word.objects.create(word_name=w, adder=u)
            wo = Word.objects.get(word_name=w)
        return wo
class _AddPropertiesForm(CremeForm):
    types = ModelMultipleChoiceField(
        label=_('Type of property'),
        queryset=CremePropertyType.objects.none(),
    )
Ejemplo n.º 25
0
class ActivityForm(ModelForm):
    """A general form, which doesn't include 'Presidency'."""
    queryset = Club.objects.current_year().visible()
    secondary_clubs = ModelMultipleChoiceField(
        queryset=queryset,
        label=Activity.secondary_clubs.field.verbose_name,
        help_text=Activity.secondary_clubs.field.help_text,
        required=False)
    episode_count = forms.CharField(widget=forms.HiddenInput())

    class Meta:
        model = Activity
        fields = [
            'name', 'category', 'description', 'public_description', 'goals',
            'gender', 'organizers', 'participants', 'secondary_clubs',
            'inside_collaborators', 'outside_collaborators', 'requirements'
        ]

    def __init__(self, *args, **kwargs):
        """
        Dynamically add date, time and location fields based on how many
        Episodes are added in the original form. The number of episodes is
        included as a hidden field with the name episode_count.
        Based on this StackOverflow thread:
        http://stackoverflow.com/questions/6142025/dynamically-add-field-to-a-form
        """
        # If an instance is passed, then store it in the instance variable.
        # This will be used in populating the episode fields when an instance
        # is passed.
        instance = kwargs.get('instance', None)

        # Initialize the form
        super(ActivityForm, self).__init__(*args, **kwargs)

        # Determine how many episodes there are:
        episode_count = 1  # default value
        # First check if an instance is passed. If true, then get the episode count of that instance
        if instance: episode_count = instance.episode_set.count()

        # If data is passed (whether it's for a new activity or editing),
        # set episode_count to the episode count within the data.
        # This may override the value obtained from the instance if there is an update in the episodes
        if self['episode_count'].value():
            episode_count = self['episode_count'].value()

        # In any case, the episode count should be at least 1
        if episode_count < 1: episode_count = 1

        #  Set the value of the hidden field to the episode count
        self.fields['episode_count'].initial = episode_count

        # If an instance is passed and is saved (has a pk), load its episodes
        if instance and instance.pk:
            instance_episodes = instance.episode_set.all()

        # Now add the custom date, time and location fields
        for i in range(int(episode_count)):
            # The disability status is the opposite of is_editable
            self.fields['episode_pk{i}'.format(i=i)] = forms.CharField(
                widget=forms.HiddenInput(), required=False)
            self.fields['start_date{i}'.format(i=i)] = forms.DateField(
                label='تاريخ البداية')
            self.fields['end_date{i}'.format(i=i)] = forms.DateField(
                label='تاريخ النهاية')
            self.fields['start_time{i}'.format(i=i)] = forms.TimeField(
                label='وقت البداية')
            self.fields['end_time{i}'.format(i=i)] = forms.TimeField(
                label='وقت النهاية')
            self.fields['location{i}'.format(i=i)] = forms.CharField(
                max_length=128, label='المكان')

            # If an instance exists (has a pk), then load the fields
            # with the instance episode values.  An IndexError arises
            # when submitting an edit form in which new episodes have
            # been added, since episode_count will increase beyond the
            # lenght of instance_episodes.  In this case just leave
            # the new fields empty as they will be filled by the
            # submitted data.
            if instance and instance.pk:
                try:
                    self.fields['episode_pk{i}'.format(
                        i=i)].initial = instance_episodes[i].pk
                    self.fields['start_date{i}'.format(
                        i=i)].initial = instance_episodes[i].start_date
                    self.fields['end_date{i}'.format(
                        i=i)].initial = instance_episodes[i].end_date
                    self.fields['start_time{i}'.format(
                        i=i)].initial = instance_episodes[i].start_time
                    self.fields['end_time{i}'.format(
                        i=i)].initial = instance_episodes[i].end_time
                    self.fields['location{i}'.format(
                        i=i)].initial = instance_episodes[i].location
                except IndexError:
                    pass

    def clean(self):
        cleaned_data = super(ActivityForm, self).clean()
        # Remove spaces at the start and end of all text fields.
        for field in cleaned_data:
            if isinstance(cleaned_data[field], unicode):
                cleaned_data[field] = cleaned_data[field].strip()
        # TODO: Check if end_date is after start_date

        return cleaned_data

    def save(self, *args, **kwargs):
        # Extract and save the episodes, perform a normal save,
        # and link the episodes to the activity

        # First, check how many episodes we have
        episode_count = self.cleaned_data['episode_count']
        new_episodes = []
        pk_list = []  # A list for storing any pk's submitted through the form
        # Comparing this list to the list of episode pk's from the
        # the database will tell us which episodes, if any, have
        # been deleted

        for i in range(int(episode_count)):
            # Get the details of each episode and store them in an Episode object
            pk = self.cleaned_data.pop('episode_pk{i}'.format(i=i), None)
            start_date = self.cleaned_data.pop('start_date{i}'.format(i=i))
            end_date = self.cleaned_data.pop('end_date{i}'.format(i=i))
            start_time = self.cleaned_data.pop('start_time{i}'.format(i=i))
            end_time = self.cleaned_data.pop('end_time{i}'.format(i=i))
            location = self.cleaned_data.pop('location{i}'.format(i=i))

            # If there is a pk, i.e. the episode already exists in the database, just update it
            # Otherwise create a new one
            if pk:
                pk_list.append(int(pk))
                episode = Episode.objects.get(pk=pk)

                episode.start_date = start_date
                episode.end_date = end_date
                episode.start_time = start_time
                episode.end_time = end_time
                episode.location = location

                episode.save()
            else:
                episode = Episode(start_date=start_date,
                                  end_date=end_date,
                                  start_time=start_time,
                                  end_time=end_time,
                                  location=location)
                new_episodes.append(episode)

        activity = super(ActivityForm, self).save(*args, **kwargs)

        # Check if any episodes have been deleted and delete them
        for episode in activity.episode_set.all():
            if episode.pk not in pk_list:
                # If the pk is not in the submitted pk's, then it has been deleted
                # by the user, so delete it from the database
                episode.delete()

        # Save the new episodes
        for episode in new_episodes:
            episode.activity = activity
            episode.save()

        return activity
Ejemplo n.º 26
0
class QuizForm(ModelForm):
    questions = ModelMultipleChoiceField(queryset=Question.objects.all())

    class Meta:
        model = Quiz
        fields = "__all__"
Ejemplo n.º 27
0
class UserAuthenticationForm(ModelForm):
    repositories = ModelMultipleChoiceField(
        label=_("Authentication repositories"),
        queryset=BaseRepository.objects.exclude(subtype="OTP").only(
            *BaseRepository.str_attrs()),
        widget=SelectMultiple(attrs={'class': 'form-control select2'}),
    )
    # Field used only by GUI, not saved
    not_openid_repositories = ModelMultipleChoiceField(
        label=_("Authentication repositories"),
        queryset=BaseRepository.objects.exclude(
            subtype__in=["OTP", "openid"]).only(*BaseRepository.str_attrs()),
        widget=SelectMultiple(attrs={'class': 'form-control select2'}),
        required=False)
    lookup_ldap_repo = ModelChoiceField(
        label=_("Lookup ldap repository"),
        queryset=LDAPRepository.objects.all().only(
            *LDAPRepository.str_attrs()),
        widget=Select(attrs={'class': 'form-control select2'}),
        required=False,
        empty_label=_("No lookup"))
    sso_forward_tls_cert = ModelChoiceField(
        label=_("Client certificate (optional)"),
        queryset=X509Certificate.objects.exclude(is_ca=True).only(
            *X509Certificate.str_attrs()),
        widget=Select(attrs={'class': 'form-control select2'}),
        required=False)
    # OAuth2 MUST uses httpS !
    external_listener = ModelChoiceField(
        label=_("Listen IDP on"),
        queryset=Frontend.objects.filter(
            enabled=True,
            mode="http",
            listener__tls_profiles__name__isnull=False).only(
                *Frontend.str_attrs()).distinct(),
        widget=Select(attrs={'class': 'form-control select2'}),
        required=False,
        empty_label=None)

    class Meta:
        model = UserAuthentication
        fields = ('name', 'enable_tracking', 'auth_type', 'portal_template',
                  'repositories', 'not_openid_repositories',
                  'lookup_ldap_repo', 'lookup_ldap_attr', 'lookup_claim_attr',
                  'user_scope', 'auth_timeout', 'enable_timeout_restart',
                  'enable_captcha', 'otp_repository', 'otp_max_retry',
                  'disconnect_url', 'enable_disconnect_message',
                  'enable_disconnect_portal', 'enable_registration',
                  'group_registration', 'update_group_registration',
                  'enable_external', 'external_fqdn', 'external_listener',
                  'enable_oauth', 'oauth_client_id', 'oauth_client_secret',
                  'oauth_redirect_uris', 'oauth_timeout', 'enable_sso_forward',
                  'sso_forward_type', 'sso_forward_direct_post',
                  'sso_forward_get_method',
                  'sso_forward_follow_redirect_before',
                  'sso_forward_follow_redirect', 'sso_forward_return_post',
                  'sso_forward_content_type', 'sso_forward_url',
                  'sso_forward_user_agent', 'sso_forward_content',
                  'sso_forward_enable_capture', 'sso_forward_capture_content',
                  'sso_forward_enable_replace', 'sso_forward_replace_pattern',
                  'sso_forward_replace_content',
                  'sso_forward_enable_additionnal',
                  'sso_forward_additional_url', 'sso_forward_tls_proto',
                  'sso_forward_tls_cert', 'sso_forward_tls_check')
        widgets = {
            'name':
            TextInput(attrs={'class': 'form-control'}),
            'enable_tracking':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'enable_external':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'external_fqdn':
            TextInput(attrs={'class': 'form-control'}),
            'auth_type':
            Select(choices=AUTH_TYPE_CHOICES,
                   attrs={'class': 'form-control select2'}),
            'user_scope':
            Select(attrs={'class': 'form-control select2'}),
            'lookup_ldap_attr':
            TextInput(attrs={'class': 'form-control'}),
            'lookup_claim_attr':
            TextInput(attrs={'class': 'form-control'}),
            'portal_template':
            Select(choices=PortalTemplate.objects.all().only(
                *PortalTemplate.str_attrs()),
                   attrs={'class': 'form-control select2'}),
            'auth_timeout':
            NumberInput(attrs={'class': 'form-control'}),
            'enable_timeout_restart':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'enable_captcha':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'otp_repository':
            Select(choices=OTPRepository.objects.all().only(
                *OTPRepository.str_attrs()),
                   attrs={'class': 'form-control select2'}),
            'otp_max_retry':
            NumberInput(attrs={'class': 'form-control'}),
            'disconnect_url':
            TextInput(attrs={'class': 'form-control'}),
            'enable_disconnect_message':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'enable_disconnect_portal':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'enable_registration':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'group_registration':
            TextInput(attrs={'class': 'form-control'}),
            'update_group_registration':
            CheckboxInput(attrs={'class': 'form-control js-switch'}),
            'enable_oauth':
            CheckboxInput(attrs={'class': 'form-control'}),
            'oauth_client_id':
            TextInput(attrs={'readonly': ''}),
            'oauth_client_secret':
            TextInput(attrs={'readonly': ''}),
            'oauth_redirect_uris':
            Textarea(attrs={'class': 'form-control'}),
            'oauth_timeout':
            NumberInput(attrs={'class': 'form-control'}),
            'enable_sso_forward':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_direct_post':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_get_method':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_follow_redirect_before':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_follow_redirect':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_return_post':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_enable_capture':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_enable_replace':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_enable_additionnal':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_type':
            Select(choices=SSO_TYPE_CHOICES,
                   attrs={'class': "form-control select2"}),
            'sso_forward_content_type':
            Select(choices=SSO_CONTENT_TYPE_CHOICES,
                   attrs={'class': "form-control select2"}),
            'sso_forward_tls_proto':
            Select(choices=TLS_PROTOCOL_CHOICES,
                   attrs={'class': "form-control select2"}),
            'sso_forward_tls_check':
            CheckboxInput(attrs={'class': "form-control js-switch"}),
            'sso_forward_url':
            TextInput(attrs={'class': "form-control"}),
            'sso_forward_user_agent':
            TextInput(attrs={'class': "form-control"}),
            'sso_forward_content':
            Textarea(attrs={
                'class': "form-control",
                'readonly': ''
            }),
            'sso_forward_capture_content':
            Textarea(attrs={'class': "form-control"}),
            'sso_forward_replace_pattern':
            Textarea(attrs={'class': "form-control"}),
            'sso_forward_replace_content':
            Textarea(attrs={'class': "form-control"}),
            'sso_forward_additional_url':
            TextInput(attrs={'class': "form-control"}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Remove the blank input generated by django
        for field_name in [
                'portal_template', 'repositories', 'auth_type',
                'sso_forward_type'
        ]:
            self.fields[field_name].empty_label = None
        self.fields['user_scope'].empty_label = "Retrieve all claims"
        self.fields['user_scope'].queryset = UserScope.objects.all()
        self.fields['otp_repository'].empty_label = "No double authentication"
        # Set fields as non required in POST data
        for field in [
                'portal_template', 'otp_repository', 'otp_max_retry',
                'group_registration', "user_scope",
                'update_group_registration', "sso_forward_direct_post",
                "sso_forward_get_method", "sso_forward_follow_redirect_before",
                "sso_forward_follow_redirect", "sso_forward_return_post",
                "sso_forward_enable_capture", "sso_forward_enable_replace",
                "sso_forward_enable_additionnal", "sso_forward_type",
                "sso_forward_content_type", "sso_forward_tls_proto",
                "sso_forward_url", "sso_forward_user_agent",
                "sso_forward_content", "sso_forward_capture_content",
                "sso_forward_replace_pattern", "sso_forward_replace_content",
                "sso_forward_additional_url"
        ]:
            self.fields[field].required = False
        # Format oauth_redirect_uris
        self.initial['oauth_redirect_uris'] = '\n'.join(
            self.initial.get('oauth_redirect_uris', [])
            or self.fields['oauth_redirect_uris'].initial)
        self.initial['not_openid_repositories'] = self.initial.get(
            'repositories')

    def clean_name(self):
        """ Replace all spaces by underscores to prevent bugs later """
        return self.cleaned_data['name'].replace(' ', '_')

    def clean_oauth_redirect_uris(self):
        """ Split values with \n """
        res = []
        for url in self.cleaned_data.get('oauth_redirect_uris',
                                         "").split("\n"):
            url = url.rstrip()
            validate = URLValidator(schemes=("http", "https"))
            validate(url)
            res.append(url)
        return res

    def clean(self):
        """ Verify required field depending on other fields """

        cleaned_data = super().clean()
        """ If external enabled, external options required """
        if cleaned_data.get('enable_external'):
            if not cleaned_data.get('external_fqdn'):
                self.add_error(
                    'external_fqdn',
                    "This field is required if external is enabled.")
            if not cleaned_data.get('external_listener'):
                self.add_error(
                    'external_listener',
                    "This field is required if external is enabled.")
        """ Portal template is required if auth_type = HTTP """
        if cleaned_data.get('auth_type') == "http" and not cleaned_data.get(
                'portal_template'):
            self.add_error('portal_template',
                           "This field is required with HTTP auth type.")
        """ otp_max_retry required if otp_repository """
        if cleaned_data.get(
                'otp_repository') and not cleaned_data.get('otp_max_retry'):
            self.add_error(
                'otp_max_retry',
                "This field is required if an OTP repository has been chosen.")
        """ disconnect_url required if enable_disconnect_message or enable_disconnect_portal """
        if cleaned_data.get('enable_disconnect_message') or cleaned_data.get(
                'enable_disconnect_portal'):
            if not cleaned_data.get('disconnect_url'):
                self.add_error(
                    'disconnect_url',
                    "This field is required if 'Disconnect message' or 'Destroy portal "
                    "session' has been enabled.")
        """ group_registration required if enable_registration """
        repo = LDAPRepository.objects.filter(
            pk=cleaned_data.get('repository')).first()
        # If enable registration with LDAP Repo : group_registration required
        if cleaned_data.get(
                'enable_registration'
        ) and repo and not cleaned_data.get('group_registration'):
            self.add_error('group_registration',
                           "This field is required if registration enabled.")
        if cleaned_data.get('enable_registration') and (cleaned_data.get('group_registration') or
                                                            cleaned_data.get('update_group_registration')) \
                and not repo:
            self.add_error(
                'group_registration',
                "To use this field, the mail repository must be LDAP.")
            self.add_error(
                'update_group_registration',
                "To use this field, the mail repository must be LDAP.")

        if cleaned_data.get('lookup_ldap_repo'):
            if not cleaned_data.get('lookup_ldap_attr'):
                self.add_error(
                    'lookup_ldap_attr',
                    "This field is required with 'LDAP Lookup repository'")
            if not cleaned_data.get('lookup_claim_attr'):
                self.add_error(
                    'lookup_claim_attr',
                    "This field is required with 'LDAP Lookup repository'")

        return cleaned_data
Ejemplo n.º 28
0
class StatMethodEditForm(BaseDefinitionsForm):

    sam_source_method_identifier = CharField(
        max_length=30, widget=TextInput(attrs={'size': 30}))
    sam_method_official_name = CharField(max_length=250,
                                         widget=Textarea(attrs={
                                             'rows': 3,
                                             'cols': 50
                                         }))
    sam_method_source = ModelChoiceField(
        queryset=MethodSourceRef.objects.all(), required=False)
    country = CharField(max_length=100, required=False)
    author = CharField(max_length=450,
                       widget=Textarea(attrs={
                           'rows': 3,
                           'cols': 50
                       }))
    sam_brief_method_summary = CharField(max_length=4000,
                                         widget=Textarea(attrs={
                                             'rows': 10,
                                             'cols': 50
                                         }))
    table_of_contents = CharField(max_length=1000,
                                  required=False,
                                  widget=Textarea(attrs={
                                      'rows': 10,
                                      'cols': 50
                                  }))
    publication_year = IntegerField(max_value=9999,
                                    min_value=0,
                                    widget=TextInput(attrs={'size': 4}))
    source_citation_name = CharField(max_length=450,
                                     widget=Textarea(attrs={
                                         'rows': 9,
                                         'cols': 50
                                     }))
    link_to_full_method = URLField(max_length=240,
                                   required=False,
                                   widget=TextInput(attrs={'size': 50}))
    notes = CharField(max_length=2000,
                      required=False,
                      widget=Textarea(attrs={
                          'rows': 9,
                          'cols': 50
                      }))
    item_type = ModelChoiceField(queryset=StatisticalItemType.objects.all())
    item_type_note = CharField(max_length=50,
                               required=False,
                               widget=TextInput(attrs={'size': 50}))
    sponser_types = ModelMultipleChoiceField(
        queryset=StatisticalSourceType.objects.all(),
        widget=CheckboxSelectMultiple)
    sponser_type_note = CharField(max_length=50,
                                  required=False,
                                  widget=TextInput(attrs={'size': 50}))
    analysis_types = ModelMultipleChoiceField(
        queryset=StatisticalAnalysisType.objects.all(),
        widget=CheckboxSelectMultiple)
    design_objectives = ModelMultipleChoiceField(
        queryset=StatisticalDesignObjective.objects.all(),
        widget=CheckboxSelectMultiple)
    sam_complexity = ChoiceField(choices=[('', '-------')] +
                                 COMPLEXITY_CHOICES)
    level_of_training = ChoiceField(choices=[('', '--------')] +
                                    LEVEL_OF_TRAINING_CHOICES)
    media_emphasized = ModelMultipleChoiceField(
        queryset=MediaNameDOM.stat_media.all(), widget=CheckboxSelectMultiple)
    media_emphasized_note = CharField(max_length=50,
                                      required=False,
                                      widget=TextInput(attrs={'size': 50}))
    media_subcategory = CharField(max_length=150,
                                  required=False,
                                  widget=TextInput(attrs={'size': 50}))
    special_topics = ModelMultipleChoiceField(
        queryset=StatisticalTopics.objects.all(),
        required=False,
        widget=CheckboxSelectMultiple)

    def get_source_citation_object(self, obj):
        ''' Returns obj with the SourceCitationRef fields filled in from the form's cleaned data
        This method assumes that the form has been validated and that cleaned_data attribute is available and
        obj should be a SourceCitationRef object.
        '''
        data = self.cleaned_data
        obj.source_citation = data['sam_source_method_identifier']
        obj.title = data['sam_method_official_name']
        obj.country = data['country']
        obj.author = data['author']
        obj.table_of_contents = data['table_of_contents']
        obj.publication_year = data['publication_year']
        obj.source_citation_name = data['source_citation_name']
        obj.link = data['link_to_full_method']
        obj.item_type = data['item_type']
        obj.item_type_note = data['item_type_note']
        obj.sponser_type_note = data['sponser_type_note']

        return obj

    def get_publication_sources(self, source_citation_ref_id):
        ''' Returns the list of PublicationSourceRelStg objects associated with source_citation_ref_id'''
        result = [
            PublicationSourceRelStg(
                source_citation_ref_id=source_citation_ref_id, source=t)
            for t in self.cleaned_data['sponser_types']
        ]
        return result

    def get_method_object(self, obj):
        ''' Returns obj with the MethodAbstract fields filled in from the form's cleaned data.
        This method assumes that the form has been validated and that the cleaned data attribute is available and
        that object is a descendant of MethodAbstract.
        '''
        data = self.cleaned_data

        obj.method_source = data['sam_method_source']
        obj.source_method_identifier = data['sam_source_method_identifier']
        obj.method_descriptive_name = data['source_citation_name']
        obj.method_official_name = data['sam_method_official_name']
        obj.brief_method_summary = data['sam_brief_method_summary']
        obj.link_to_full_method = data['link_to_full_method']
        obj.notes = data['notes']
        obj.sam_complexity = data['sam_complexity']
        obj.level_of_training = data['level_of_training']
        obj.media_emphasized_note = data['media_emphasized_note']
        obj.media_subcategory = data['media_subcategory']

        return obj

    def get_analysis_types(self, method_id):
        '''Returns a list of StatAnalysisRelStg objects associated with method_id'''
        result = [
            StatAnalysisRelStg(method_id=method_id, analysis_type=t)
            for t in self.cleaned_data['analysis_types']
        ]
        return result

    def get_design_objectives(self, method_id):
        '''Returns a list of StatDesignRelStg objects associated with method_id'''
        result = [
            StatDesignRelStg(method_id=method_id, design_objective=t)
            for t in self.cleaned_data['design_objectives']
        ]
        return result

    def get_media_emphasized(self, method_id):
        '''Returns a list of StatMediaRelStg objects associated with method_id'''
        result = [
            StatMediaRelStg(method_id=method_id, media_name=t)
            for t in self.cleaned_data['media_emphasized']
        ]
        return result

    def get_special_topics(self, method_id):
        '''Returns a list of StatTopicRelStg objects associated with method_id'''
        result = [
            StatTopicRelStg(method_id=method_id, topic=t)
            for t in self.cleaned_data['special_topics']
        ]
        return result
Ejemplo n.º 29
0
class ChampionshipForm(ModelForm):
    teams = ModelMultipleChoiceField(queryset=JIFsTeam.objects.all(), required=False, label='Times')

    class Meta:
        model = Championship
        fields = '__all__'
Ejemplo n.º 30
0
class GroupForm(PermissionFormMixin, ModelForm):
    can_view_past_event = PermissionField(
        label=_("Can view past events"), permissions=["core.view_past_event"], required=False
    )

    is_planning_group = PermissionField(
        label=_("Can add events"),
        permissions=["core.add_event", "core.delete_event"],
        required=False,
    )
    publish_event_for_group = ModelMultipleChoiceField(
        label=_("Can publish events for groups"),
        queryset=Group.objects.all(),
        required=False,
        help_text=_("Choose groups that this group can make events visible for."),
        widget=Select2MultipleWidget,
    )
    decide_workinghours_for_group = ModelMultipleChoiceField(
        label=_("Can decide working hours for groups"),
        queryset=Group.objects.all(),
        required=False,
        help_text=_(
            "Choose groups that the group you are currently editing can decide whether to grant working hours for."
        ),
        widget=Select2MultipleWidget,
    )

    is_hr_group = PermissionField(
        label=_("Can edit users"),
        help_text=_(
            "If checked, users in this group can view, add, edit and delete users. They can also manage group memberships for their own groups."
        ),
        permissions=[
            "core.add_userprofile",
            "core.change_userprofile",
            "core.delete_userprofile",
            "core.view_userprofile",
        ],
        required=False,
    )
    is_management_group = PermissionField(
        label=_("Can manage ephios"),
        help_text=_(
            "If checked, users in this group can manage users, groups, all group memberships, eventtypes and qualifications"
        ),
        permissions=[
            "auth.add_group",
            "auth.change_group",
            "auth.delete_group",
            "auth.view_group",
            "core.add_userprofile",
            "core.change_userprofile",
            "core.delete_userprofile",
            "core.view_userprofile",
            "core.view_event",
            "core.add_event",
            "core.change_event",
            "core.delete_event",
            "core.view_eventtype",
            "core.add_eventtype",
            "core.change_eventtype",
            "core.delete_eventtype",
            "core.view_qualification",
            "core.add_qualification",
            "core.change_qualification",
            "core.delete_qualification",
        ],
        required=False,
    )

    users = ModelMultipleChoiceField(
        label=_("Users"), queryset=UserProfile.objects.all(), widget=MultiUserProfileWidget
    )

    class Meta:
        model = Group
        fields = ["name"]

    def __init__(self, **kwargs):
        if (group := kwargs.get("instance", None)) is not None:
            kwargs["initial"] = {
                "users": group.user_set.all(),
                "publish_event_for_group": get_objects_for_group(
                    group, "publish_event_for_group", klass=Group
                ),
                "decide_workinghours_for_group": get_objects_for_group(
                    group, "decide_workinghours_for_group", klass=Group
                ),
                **kwargs.get("initial", {}),
            }
            self.permission_target = group
        super().__init__(**kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field("name"),
            Field("users"),
            Field("can_view_past_event"),
            Fieldset(
                _("Management"),
                Field("is_hr_group", title="This permission is included with the management role."),
                "is_management_group",
            ),
            Fieldset(
                _("Planning"),
                Field(
                    "is_planning_group",
                    title="This permission is included with the management role.",
                ),
                Field("publish_event_for_group", wrapper_class="publish-select"),
                "decide_workinghours_for_group",
            ),
            FormActions(Submit("submit", _("Save"))),
        )