Exemple #1
0
    def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES,
                 choices=CURRENCY_CHOICES, max_value=None, min_value=None,
                 max_digits=None, decimal_places=None, *args, **kwargs):

        # choices does not make sense in this context, it would mean we had
        # to replace two widgets with one widget dynamically... which is a
        # mess. Instead, we let currency_choices be the same as choices and
        # raise a warning.
        if currency_choices != CURRENCY_CHOICES:
            warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning)
            choices = currency_choices

        amount_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs)
        currency_field = ChoiceField(choices=choices)

        if VERSION < (1, 10) and hasattr(amount_field, '_has_changed') and hasattr(currency_field, '_has_changed'):
            amount_field.has_changed = amount_field._has_changed
            currency_field.has_changed = currency_field._has_changed

        # TODO: No idea what currency_widget is supposed to do since it doesn't
        # even receive currency choices as input. Somehow it's supposed to be
        # instantiated from outside. Hard to tell.
        if currency_widget:
            self.widget = currency_widget
        else:
            self.widget = MoneyWidget(
                amount_widget=amount_field.widget,
                currency_widget=currency_field.widget
            )

        # The two fields that this widget comprises
        fields = (amount_field, currency_field)
        super(MoneyField, self).__init__(fields, *args, **kwargs)
 def test_regression_5216_b(self):
     # Testing choice validation with UTF-8 bytestrings as input (these are the
     # Russian abbreviations "мес." and "шт.".
     UNITS = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'),
              (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.'))
     f = ChoiceField(choices=UNITS)
     self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.')
     self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.')
Exemple #3
0
 def test_utf8_bytesrings(self):
     # Choice validation with UTF-8 bytestrings as input (these are the
     # Russian abbreviations "мес." and "шт.".
     f = ChoiceField(
         choices=(
             (b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'),
             (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.'),
         ),
     )
     self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.')
     self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.')
 def test_choicefield_1(self):
     f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')])
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean('')
     with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
         f.clean(None)
     self.assertEqual('1', f.clean(1))
     self.assertEqual('1', f.clean('1'))
     msg = "'Select a valid choice. 3 is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('3')
 def test_choicefield_4(self):
     f = ChoiceField(
         choices=[
             ('Numbers', (('1', 'One'), ('2', 'Two'))),
             ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other'),
         ]
     )
     self.assertEqual('1', f.clean(1))
     self.assertEqual('1', f.clean('1'))
     self.assertEqual('3', f.clean(3))
     self.assertEqual('3', f.clean('3'))
     self.assertEqual('5', f.clean(5))
     self.assertEqual('5', f.clean('5'))
     msg = "'Select a valid choice. 6 is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('6')
 class SomeForm(Form):
     field = ChoiceField(choices=[('one', 'One')])
Exemple #7
0
class TaskForm(ModelForm):
    problem_category = ModelChoiceField(queryset=TaskCategory.objects.filter(
        stage=TaskCategory.Stage.INITIAL_ASSESSMENT),
                                        required=False,
                                        label="Problem category")
    resolution_category = ModelChoiceField(
        queryset=TaskCategory.objects.filter(
            stage=TaskCategory.Stage.COMPLETION),
        required=False,
        label="Resolution category")
    action = ChoiceField(choices=[('create', 'create'), ('update', 'update'),
                                  ('resolve', 'resolve')],
                         label="Action")
    description = CharField(required=False, label="Description")

    class Meta:
        model = Task
        fields = [
            'tool', 'urgency', 'estimated_resolution_time', 'force_shutdown',
            'safety_hazard'
        ]

    def __init__(self, user, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        self.user = user
        self.fields['tool'].required = False
        self.fields['urgency'].required = False

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

    def clean(self):
        if any(self.errors):
            return
        super(TaskForm, self).clean()
        action = self.cleaned_data['action']
        if action == 'create':
            if not self.cleaned_data['description']:
                raise ValidationError('You must describe the problem.')
        if action == 'resolve':
            if self.instance.cancelled or self.instance.resolved:
                raise ValidationError(
                    "This task can't be resolved because it is marked as 'cancelled' or 'resolved' already."
                )

    def save(self, commit=True):
        instance = super(TaskForm, self).save(commit=False)
        action = self.cleaned_data['action']
        description = self.cleaned_data['description']
        instance.problem_category = self.cleaned_data['problem_category']
        now = timezone.now()
        if action == 'create':
            instance.problem_description = description
            instance.urgency = Task.Urgency.HIGH if self.cleaned_data[
                'force_shutdown'] or self.cleaned_data[
                    'safety_hazard'] else Task.Urgency.NORMAL
            instance.creator = self.user
        if action == 'update':
            instance.last_updated = timezone.now()
            instance.last_updated_by = self.user
            instance.cancelled = False
            instance.resolved = False
            if description:
                preface = f'On {format_datetime(now)} {self.user.get_full_name()} updated this task:\n'
                if instance.progress_description is None:
                    instance.progress_description = preface + description
                else:
                    instance.progress_description += '\n\n' + preface + description
                instance.progress_description = instance.progress_description.strip(
                )
        if action == 'resolve':
            instance.cancelled = False
            instance.resolved = True
            instance.resolution_time = now
            instance.resolver = self.user
            if 'resolution_category' in self.cleaned_data:
                instance.resolution_category = self.cleaned_data[
                    'resolution_category']
            if 'description' in self.cleaned_data:
                if instance.resolution_description:
                    preface = f'On {format_datetime(now)} {self.user.get_full_name()} updated the resolution information:\n'
                    instance.resolution_description = (
                        instance.resolution_description + '\n\n' + preface +
                        self.cleaned_data['description']).strip()
                else:
                    instance.resolution_description = self.cleaned_data[
                        'description']
        return super(TaskForm, self).save(commit=True)
Exemple #8
0
    def __init__(self,
                 request=None,
                 author=None,
                 expire_date=None,
                 *args,
                 **kwargs):
        super().__init__(*args, **kwargs)

        # remember author if this form is saved
        self.author = author or request.user
        author_permissions = request.user_permissions if request else author.permissions

        self.expire_date = expire_date

        # determine which access permissions the author can grant
        self.author_access_permissions = AccessPermission.get_for_request_with_expire_date(
            request, can_grant=True)

        access_restrictions = AccessRestriction.objects.filter(
            pk__in=self.author_access_permissions.keys())

        self.access_restrictions = {
            access_restriction.pk: access_restriction
            for access_restriction in access_restrictions
        }
        access_restrictions_ids = set(self.access_restrictions.keys())

        self.access_restriction_choices = {
            'all': self.access_restrictions.values(),
            **{
                str(pk): (access_restriction, )
                for pk, access_restriction in self.access_restrictions.items()
            }
        }

        # get access permission groups
        groups = AccessRestrictionGroup.qs_for_request(
            request).prefetch_related(
                Prefetch('accessrestrictions',
                         AccessRestriction.objects.only('pk')))
        group_contents = {
            group.pk: set(r.pk for r in group.accessrestrictions.all())
            for group in groups
        }
        group_contents = {
            pk: restrictions
            for pk, restrictions in group_contents.items()
            if not (restrictions - access_restrictions_ids)
        }

        self.access_restriction_choices.update({
            ('g%d' % pk): tuple(self.access_restrictions[restriction]
                                for restriction in restrictions)
            for pk, restrictions in group_contents.items()
        })

        # construct choice field for access permissions
        choices = [('', _('choose permissions…')),
                   ('all',
                    ungettext_lazy('everything possible (%d permission)',
                                   'everything possible (%d permissions)',
                                   len(access_restrictions)) %
                    len(access_restrictions))]

        choices.append(
            (_('Access Permission Groups'),
             tuple(('g%d' % group.pk, group.title) for group in groups)))
        choices.append((_('Access Permissions'),
                        tuple((str(pk), access_restriction.title)
                              for pk, access_restriction in
                              self.access_restrictions.items())))

        self.fields['access_restrictions'] = ChoiceField(choices=choices,
                                                         required=True)

        # construct choices for the expire field
        expire_choices = [
            ('', _('never')),
        ]
        for minutes in range(15, 60, 15):
            expire_choices.append(
                (str(minutes),
                 ungettext_lazy('in %d minute', 'in %d minutes', minutes) %
                 minutes))

        for hours in chain(range(1, 6), range(6, 24, 6)):
            expire_choices.append(
                (str(hours * 60),
                 ungettext_lazy('in %d hour', 'in %d hours', hours) % hours))
        expire_choices.insert(5, (str(90), _('in 1½ hour')))
        for days in range(1, 14):
            expire_choices.append(
                (str(days * 24 * 60),
                 ungettext_lazy('in %d day', 'in %d days', days) % days))

        self.fields['expires'] = ChoiceField(required=False,
                                             initial='60',
                                             choices=expire_choices)

        # if applicable, add field to grant pass on permissions
        if author_permissions.grant_all_access:
            choices = [('0', '---')] * 6 + [('1', _('can pass on'))
                                            ] + [('0', '---')] * 3
            self.fields['can_grant'] = ChoiceField(required=False,
                                                   initial='60',
                                                   choices=choices)
Exemple #9
0
class _ExampleForm(Form):
    single = ChoiceField(choices=((1, "one"), (2, "two"), (3, "three")), required=False)
    multi = MultipleChoiceField(
        choices=((1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five")),
        required=False,
    )
Exemple #10
0
class ThreadListGetForm(_PaginationForm):
    """
    A form to validate query parameters in the thread list retrieval endpoint
    """
    EXCLUSIVE_PARAMS = ["topic_id", "text_search", "following"]

    course_id = CharField()
    topic_id = MultiValueField(required=False)
    text_search = CharField(required=False)
    following = ExtendedNullBooleanField(required=False)
    author = CharField(required=False)
    thread_type = ChoiceField(
        choices=[(choice, choice) for choice in ["discussion", "question"]],
        required=False,
    )
    count_flagged = ExtendedNullBooleanField(required=False)
    flagged = ExtendedNullBooleanField(required=False)
    view = ChoiceField(
        choices=[(choice, choice) for choice in ["unread", "unanswered"]],
        required=False,
    )
    order_by = ChoiceField(
        choices=[(choice, choice) for choice in ["last_activity_at", "comment_count", "vote_count"]],
        required=False
    )
    order_direction = ChoiceField(
        choices=[(choice, choice) for choice in ["desc"]],
        required=False
    )
    requested_fields = MultiValueField(required=False)

    def clean_order_by(self):
        """Return a default choice"""
        return self.cleaned_data.get("order_by") or "last_activity_at"

    def clean_order_direction(self):
        """Return a default choice"""
        return self.cleaned_data.get("order_direction") or "desc"

    def clean_course_id(self):
        """Validate course_id"""
        value = self.cleaned_data["course_id"]
        try:
            return CourseLocator.from_string(value)
        except InvalidKeyError:
            raise ValidationError(f"'{value}' is not a valid course id")  # lint-amnesty, pylint: disable=raise-missing-from

    def clean_following(self):
        """Validate following"""
        value = self.cleaned_data["following"]
        if value is False:  # lint-amnesty, pylint: disable=no-else-raise
            raise ValidationError("The value of the 'following' parameter must be true.")
        else:
            return value

    def clean(self):
        cleaned_data = super().clean()
        exclusive_params_count = sum(
            1 for param in self.EXCLUSIVE_PARAMS if cleaned_data.get(param)
        )
        if exclusive_params_count > 1:
            raise ValidationError(
                "The following query parameters are mutually exclusive: {}".format(
                    ", ".join(self.EXCLUSIVE_PARAMS)
                )
            )
        return cleaned_data
Exemple #11
0
class JumbotronFormMixin(EntangledModelFormMixin):
    """
    Form class to validate the JumbotronPlugin.
    """
    ATTACHMENT_CHOICES = ['scroll', 'fixed', 'local']
    VERTICAL_POSITION_CHOICES = [
        'top', '10%', '20%', '30%', '40%', 'center', '60%', '70%', '80%',
        '90%', 'bottom'
    ]
    HORIZONTAL_POSITION_CHOICES = [
        'left', '10%', '20%', '30%', '40%', 'center', '60%', '70%', '80%',
        '90%', 'right'
    ]
    REPEAT_CHOICES = ['repeat', 'repeat-x', 'repeat-y', 'no-repeat']
    SIZE_CHOICES = ['auto', 'width/height', 'cover', 'contain']

    fluid = BooleanField(
        label=_("Is fluid"),
        initial=True,
        required=False,
        help_text=
        _("Shall this element occupy the entire horizontal space of its parent."
          ),
    )

    element_heights = BootstrapMultiSizeField(
        label=("Element Heights"),
        required=True,
        allowed_units=['rem', 'px'],
        initial='300px',
        help_text=_(
            "This property specifies the height for each Bootstrap breakpoint."
        ),
    )

    background_color = ColorField(label=_("Background color"), )

    image_file = CascadeImageField(
        label=_("Background image"),
        required=False,
    )

    background_repeat = ChoiceField(
        label=_("Background repeat"),
        choices=[(c, c) for c in REPEAT_CHOICES],
        widget=widgets.RadioSelect,
        initial='no-repeat',
        required=False,
        help_text=_(
            "This property specifies how the background image repeates."),
    )

    background_attachment = ChoiceField(
        label=_("Background attachment"),
        choices=[(c, c) for c in ATTACHMENT_CHOICES],
        widget=widgets.RadioSelect,
        initial='local',
        required=False,
        help_text=
        _("This property specifies how to move the background image relative to the viewport."
          ),
    )

    background_vertical_position = ChoiceField(
        label=_("Background vertical position"),
        choices=[(c, c) for c in VERTICAL_POSITION_CHOICES],
        initial='center',
        required=False,
        help_text=
        _("This property moves a background image vertically within its container."
          ),
    )

    background_horizontal_position = ChoiceField(
        label=_("Background horizontal position"),
        choices=[(c, c) for c in HORIZONTAL_POSITION_CHOICES],
        initial='center',
        required=False,
        help_text=
        _("This property moves a background image horizontally within its container."
          ),
    )

    background_size = ChoiceField(
        label=_("Background size"),
        choices=[(c, c) for c in SIZE_CHOICES],
        widget=widgets.RadioSelect,
        initial='auto',
        required=False,
        help_text=_(
            "This property specifies how the background image is sized."),
    )

    background_width_height = MultiSizeField(
        ['width', 'height'],
        label=_("Background width/height"),
        allowed_units=['px', '%'],
        required=False,
        help_text=
        _("This property specifies the width and height of a background image in px or %."
          ),
    )

    class Meta:
        entangled_fields = {
            'glossary': [
                'fluid', 'background_color', 'element_heights', 'image_file',
                'background_repeat', 'background_attachment',
                'background_vertical_position',
                'background_horizontal_position', 'background_size',
                'background_width_height'
            ]
        }

    def validate_optional_field(self, name):
        field = self.fields[name]
        value = field.widget.value_from_datadict(self.data, self.files,
                                                 self.add_prefix(name))
        if value in field.empty_values:
            self.add_error(
                name,
                ValidationError(field.error_messages['required'],
                                code='required'))
        else:
            return value

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data['image_file']:
            self.validate_optional_field('background_repeat')
            self.validate_optional_field('background_attachment')
            self.validate_optional_field('background_vertical_position')
            self.validate_optional_field('background_horizontal_position')
            if self.validate_optional_field(
                    'background_size') == 'width/height':
                try:
                    cleaned_data['background_width_height']['width']
                except KeyError:
                    msg = _("You must at least set a background width.")
                    self.add_error('background_width_height', msg)
                    raise ValidationError(msg)
        return cleaned_data
Exemple #12
0
class TaskForm(ModelForm):
    problem_category = ModelChoiceField(
        queryset=TaskCategory.objects.filter(
            stage=TaskCategory.Stage.INITIAL_ASSESSMENT),
        required=False,
        label="Problem category",
    )
    resolution_category = ModelChoiceField(
        queryset=TaskCategory.objects.filter(
            stage=TaskCategory.Stage.COMPLETION),
        required=False,
        label="Resolution category",
    )
    action = ChoiceField(choices=[("create", "create"), ("update", "update"),
                                  ("resolve", "resolve")],
                         label="Action")
    description = CharField(required=False, label="Description")

    class Meta:
        model = Task
        fields = [
            "tool", "urgency", "estimated_resolution_time", "force_shutdown",
            "safety_hazard"
        ]

    def __init__(self, user, *args, **kwargs):
        super(TaskForm, self).__init__(*args, **kwargs)
        self.user = user
        self.fields["tool"].required = False
        self.fields["urgency"].required = False

    def clean_description(self):
        return self.cleaned_data["description"].strip()

    def clean(self):
        if any(self.errors):
            return
        super(TaskForm, self).clean()
        action = self.cleaned_data["action"]
        if action == "create":
            if not self.cleaned_data["description"]:
                raise ValidationError("You must describe the problem.")
        if action == "resolve":
            if self.instance.cancelled or self.instance.resolved:
                raise ValidationError(
                    "This task can't be resolved because it is marked as 'cancelled' or 'resolved' already."
                )

    def save(self, commit=True):
        instance = super(TaskForm, self).save(commit=False)
        action = self.cleaned_data["action"]
        description = self.cleaned_data["description"]
        instance.problem_category = self.cleaned_data["problem_category"]
        now = timezone.now()
        if action == "create":
            instance.problem_description = description
            instance.urgency = (
                Task.Urgency.HIGH if self.cleaned_data["force_shutdown"]
                or self.cleaned_data["safety_hazard"] else Task.Urgency.NORMAL)
            instance.creator = self.user
        if action == "update":
            instance.last_updated = timezone.now()
            instance.last_updated_by = self.user
            instance.cancelled = False
            instance.resolved = False
            if description:
                preface = f"On {format_datetime(now)} {self.user.get_full_name()} updated this task:\n"
                if instance.progress_description is None:
                    instance.progress_description = preface + description
                else:
                    instance.progress_description += "\n\n" + preface + description
                instance.progress_description = instance.progress_description.strip(
                )
        if action == "resolve":
            instance.cancelled = False
            instance.resolved = True
            instance.resolution_time = now
            instance.resolver = self.user
            if "resolution_category" in self.cleaned_data:
                instance.resolution_category = self.cleaned_data[
                    "resolution_category"]
            if "description" in self.cleaned_data:
                if instance.resolution_description:
                    preface = (
                        f"On {format_datetime(now)} {self.user.get_full_name()} updated the resolution information:\n"
                    )
                    instance.resolution_description = (
                        instance.resolution_description + "\n\n" + preface +
                        self.cleaned_data["description"]).strip()
                else:
                    instance.resolution_description = self.cleaned_data[
                        "description"]
        return super(TaskForm, self).save(commit=True)
class JumbotronFormMixin(EntangledModelFormMixin):
    """
    Form class to validate the JumbotronPlugin.
    """
    ATTACHMENT_CHOICES = ['scroll', 'fixed', 'local']
    VERTICAL_POSITION_CHOICES = [
        'top', '10%', '20%', '30%', '40%', 'center', '60%', '70%', '80%',
        '90%', 'bottom'
    ]
    HORIZONTAL_POSITION_CHOICES = [
        'left', '10%', '20%', '30%', '40%', 'center', '60%', '70%', '80%',
        '90%', 'right'
    ]
    REPEAT_CHOICES = ['repeat', 'repeat-x', 'repeat-y', 'no-repeat']
    SIZE_CHOICES = ['auto', 'width/height', 'cover', 'contain']

    background_color = ColorField(label=_("Background color"), )

    background_repeat = ChoiceField(
        label=_("Background repeat"),
        choices=[(c, c) for c in REPEAT_CHOICES],
        widget=widgets.RadioSelect,
        initial='no-repeat',
        help_text=_("This property specifies how an image repeates."),
    )

    background_attachment = ChoiceField(
        label=_("Background attachment"),
        choices=[(c, c) for c in ATTACHMENT_CHOICES],
        widget=widgets.RadioSelect,
        initial='local',
        help_text=
        _("This property specifies how to move the background relative to the viewport."
          ),
    )

    background_vertical_position = ChoiceField(
        label=_("Background vertical position"),
        choices=[(c, c) for c in VERTICAL_POSITION_CHOICES],
        initial='center',
        help_text=
        _("This property moves a background image vertically within its container."
          ),
    )

    background_horizontal_position = ChoiceField(
        label=_("Background horizontal position"),
        choices=[(c, c) for c in HORIZONTAL_POSITION_CHOICES],
        initial='center',
        help_text=
        _("This property moves a background image horizontally within its container."
          ),
    )

    background_size = ChoiceField(
        label=_("Background size"),
        choices=[(c, c) for c in SIZE_CHOICES],
        widget=widgets.RadioSelect,
        initial='auto',
        help_text=_("This property specifies how an image is sized."),
    )

    background_width_height = MultiSizeField(
        ['width', 'height'],
        label=_("Background width/height"),
        allowed_units=['px', '%'],
        required=False,
        help_text=
        _("This property specifies the width and height of a background image in px or %."
          ),
    )

    class Meta:
        entangled_fields = {
            'glossary': [
                'background_color', 'background_repeat',
                'background_attachment', 'background_vertical_position',
                'background_horizontal_position', 'background_size',
                'background_width_height'
            ]
        }

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data['background_size'] == 'width/height':
            try:
                cleaned_data['background_width_height']['width']
            except KeyError:
                msg = _("You must at least set a background width.")
                self.add_error('background_width_height', msg)
                raise ValidationError(msg)
        return cleaned_data
Exemple #14
0
class LicenceForm(forms.ModelForm):
    """Base form for licences."""
    class Meta:
        fieldset = OrderedDict([
            ('Basic info', [
                'asset_type',
                'manufacturer',
                'licence_type',
                'software_category',
                'parent',
                'niw',
                'sn',
                'property_of',
                'valid_thru',
                'assets',
                'users',
                'remarks',
                'service_name',
                'license_details',
            ]),
            ('Financial info', [
                'order_no',
                'invoice_date',
                'invoice_no',
                'price',
                'provider',
                'number_bought',
                'accounting_id',
                'budget_info',
            ]),
        ])
        widgets = {
            'invoice_date': DateWidget,
            'license_details': forms.Textarea(attrs={'rows': 3}),
            'remarks': forms.Textarea(attrs={'rows': 3}),
            'sn': forms.Textarea(attrs={'rows': 3}),
            'valid_thru': DateWidget,
        }

    asset_type = ChoiceField(
        required=True,
        choices=[('', '----')] +
        [(choice.id, choice.name)
         for choice in [AssetType.back_office, AssetType.data_center]],
    )
    parent = AutoCompleteSelectField(
        ('ralph_assets.models', 'LicenceLookup'),
        required=False,
        label=_('Parent licence'),
    )
    software_category = SoftwareCategoryField(
        ('ralph_assets.models', 'SoftwareCategoryLookup'),
        widget=SoftwareCategoryWidget,
        plugin_options=dict(
            add_link='/admin/ralph_assets/softwarecategory/add/?name=', ))
    manufacturer = AutoCompleteSelectField(
        ('ralph_assets.models', 'ManufacturerLookup'),
        widget=AutoCompleteWidget,
        plugin_options=dict(
            add_link='/admin/ralph_assets/assetmanufacturer/add/', ),
        required=False,
    )
    budget_info = AutoCompleteSelectField(
        LOOKUPS['budget_info'],
        required=False,
        plugin_options=dict(add_link='/admin/ralph_assets/budgetinfo/add/', ))
    assets = AutoCompleteSelectMultipleField(LOOKUPS['linked_device'],
                                             required=False,
                                             label=_('Assigned Assets'))
    users = AutoCompleteSelectMultipleField(LOOKUPS['asset_user'],
                                            required=False,
                                            label=_('Assigned Users'))

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

    def clean(self, *args, **kwargs):
        result = super(LicenceForm, self).clean(*args, **kwargs)
        if len(result.get('assets', [])) > result.get('number_bought'):
            raise forms.ValidationError(
                _("You don't have sufficient licences!"))
        if 'software_category' not in result:
            return result
        if result['software_category'].asset_type is None:
            result['software_category'].asset_type = MODE2ASSET_TYPE[self.mode]
        if result['software_category'].pk is None:
            result['software_category'].save()
        return result
Exemple #15
0
    def test_choicefield_callable(self):
        def choices():
            return [('J', 'John'), ('P', 'Paul')]

        f = ChoiceField(choices=choices)
        self.assertEqual('J', f.clean('J'))
Exemple #16
0
 def test_choicefield_disabled(self):
     f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True)
     self.assertWidgetRendersTo(
         f,
         '<select id="id_f" name="f" disabled required><option value="J">John</option>'
         '<option value="P">Paul</option></select>')
Exemple #17
0
 def test_choicefield_3(self):
     f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
     self.assertEqual('J', f.clean('J'))
     msg = "'Select a valid choice. John is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('John')
Exemple #18
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['contact'] = ChoiceField(label='Select contact', choices=[(d.id, str(d)) for d in Contact.objects.all()])
Exemple #19
0
class ChoiceForm(Form):
    CHOICE_LIST = [('pizza', 'Pizza'), ('sub', 'Sub'), ('pasta', 'Pasta'),
                   ('salad', 'Salad'), ('platter', 'Platter')]
    choice = ChoiceField(choices=CHOICE_LIST, required=True)
Exemple #20
0
class LogSearchForm(Form):
    class FormNotValid(StandardError):
        pass

    import logging

    #matrix parameters for call
    type = MultipleChoiceField(choices=(
        ('all', 'All'),
        ('DELETE_LIBRARY', 'DELETE_LIBRARY'),
        ('UPDATE_LIBRARY_ITEM_METADATA', 'UPDATE_LIBRARY_ITEM_METADATA'),
        ('NONE', 'NONE'),
        ('IMPORT', 'IMPORT'),
        ('TRANSCODE', 'TRANSCODE'),
        ('RAW_TRANSCODE', 'RAW_TRANSCODE'),
        ('CONFORM', 'CONFORM'),
        ('TRANSCODE_RANGE', 'TRANSCODE_RANGE'),
        ('PLACEHOLDER_IMPORT', 'PLACEHOLDER_IMPORT'),
        ('RAW_IMPORT', 'RAW_IMPORT'),
        ('THUMBNAIL', 'THUMBNAIL'),
        ('AUTO_IMPORT', 'AUTO_IMPORT'),
        ('EXPORT', 'EXPORT'),
        ('COPY_FILE', 'COPY_FILE'),
        ('DELETE_FILE', 'DELETE_FILE'),
        ('MOVE_FILE', 'MOVE_FILE'),
        ('ESSENCE_VERSION', 'ESSENCE_VERSION'),
        ('FCS_RESTORE', 'FCS_RESTORE'),
        ('TIMELINE', 'TIMELINE'),
        ('SHAPE_IMPORT', 'SHAPE_IMPORT'),
        ('LIST_ITEMS', 'LIST_ITEMS'),
        ('ANALYZE', 'ANALYZE'),
        ('SHAPE_UPDATE', 'SHAPE_UPDATE'),
        ('ARCHIVE', 'ARCHIVE'),
        ('RESTORE', 'RESTORE'),
        ('SIDECAR_IMPORT', 'SIDECAR_IMPORT'),
        ('TEST_TRANSFER', 'TEST_TRANSFER'),
    ),
                               widget=CheckboxSelectMultiple())
    state = MultipleChoiceField(
        choices=(
            ('all', 'All'),
            ('NONE', 'None'),
            ('READY', 'Ready'),
            ('STARTED', 'Started'),
            ('STARTED_ASYNCHRONOUS', 'Started Asynchronous'),
            ('STARTED_PARALLEL', 'Started in background'),
            ('STARTED_PARALLEL_ASYNCHRONOUS',
             'Started in background, asynchronous'),
            ('STARTED_SUBTASKS', 'Started and doing in multiple subtasks'),
            ('FINISHED', 'Completed'),
            ('FAILED_RETRY', 'Retrying'),
            ('FAILED_FATAL', 'Failed'),
            ('FAILED_TOTAL', 'Failed'),
            ('WAITING', 'Waiting'),  #see /job/{job-id}/problem
            ('DISAPPEARED', 'Disappeared, lost worker')),
        widget=CheckboxSelectMultiple())
    sort = ChoiceField(choices=(
        ('startTime', 'Start Time'),
        ('priority', 'Priority'),
        ('jobId', 'Job ID'),
        ('type', 'Type'),
        ('state', 'State'),
        ('user', 'User'),
    ),
                       widget=Select(attrs={'style': 'width: 98%'}))
    sortOrder = ChoiceField(
        choices=(
            ('desc', 'Descending'),
            ('asc', 'Ascending'),
        ),
        widget=RadioSelect(),
    )
    fromDate = DateField(label="Starting from",
                         widget=TextInput(attrs={'style': 'width: 60%'}))
    fromTime = TimeField(label="Starting from",
                         widget=TextInput(attrs={'style': 'width: 60%'}))

    toDate = DateField(label="Ending at",
                       widget=TextInput(attrs={'style': 'width: 60%'}))
    toTime = TimeField(label="Ending at",
                       widget=TextInput(attrs={'style': 'width: 60%'}))

    #Query parameters for call
    jobmetadata = CharField(max_length=32768, widget=Textarea, required=False)

    #my own params which will be put into the above
    fileNameContains = CharField(
        max_length=512,
        widget=TextInput(attrs={'style': 'width: 98%; visibility: hidden'}),
        required=False)

    columns = MultipleChoiceField(choices=(
        ('jobId', 'jobId'),
        ('status', 'status'),
        ('type', 'type'),
        ('started', 'started'),
        ('priority', 'priority'),
        ('itemid', 'itemid'),
        ('systemJobModule', 'systemJobModule'),
        ('systemJobInfo', 'systemJobInfo'),
        ('destinationStorageId', 'destinationStorageId'),
        ('bestEffortFilename', 'bestEffortFilename'),
        ('fileId', 'fileId'),
        ('replicatedFileIds', 'replicatedFileIds'),
        ('fileDeleted', 'fileDeleted'),
        ('fileStateOnFailure', 'fileStateOnFailure'),
        ('filePathMap', 'filePathMap'),
        ('replicatedFileInfo', 'replicatedFileInfo'),
        ('checkReplicatedFiles', 'checkReplicatedFiles'),
    ),
                                  widget=CheckboxSelectMultiple())

    def vidispine_query_url(self, base, page):
        from datetime import datetime
        import time
        import calendar

        if not self.is_valid():
            raise self.FormNotValid()

        #logger=self.logging.getLogger("LogSearchForm::vidispine_query_url")
        d = self.cleaned_data

        if page == 1:
            pagesetting = 0
        else:
            pagesetting = page * 100 - 100

        pagesettingready = str(pagesetting)

        matrixparams = ""
        if not 'all' in d['state']:
            matrixparams += ";state=" + ",".join(
                map(lambda x: urllib.quote_plus(x, safe=""), d['state']))
        if not 'all' in d['type']:
            matrixparams += ";type=" + ",".join(
                map(lambda x: urllib.quote_plus(x, safe=""), d['type']))
        matrixparams += ";number=100;first=" + pagesettingready + ";sort={0}%20{1}".format(
            urllib.quote_plus(d['sort'], safe=""), d['sortOrder'])
        queryparams = "?metadata=true"

        if d['fileNameContains']:
            queryparams += "&jobmetadata=" + urllib.quote_plus(
                "bestEffortFilename=*{0}*".format(d['fileNameContains']),
                safe="")

        if d['jobmetadata']:
            queryparams += "&jobmetadata=" + urllib.quote_plus(
                d['jobmetadata'], safe="")

        fromTime = datetime.combine(d['fromDate'], d['fromTime'])
        toTime = datetime.combine(d['toDate'], d['toTime'])
        queryparams += "&starttime-from=" + urllib.quote_plus(
            fromTime.strftime("%Y-%m-%dT%H:%M:%S.%f"), safe="")
        queryparams += "&starttime-to=" + urllib.quote_plus(
            toTime.strftime("%Y-%m-%dT%H:%M:%S.%f"), safe="")

        print "debug: vidispine_query_url is {0}".format(base + matrixparams +
                                                         queryparams)
        return base + matrixparams + queryparams
 def test_choicefield_3(self):
     f = ChoiceField(choices=[("J", "John"), ("P", "Paul")])
     self.assertEqual("J", f.clean("J"))
     msg = "'Select a valid choice. John is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean("John")
Exemple #22
0
 class ImportProjectsForm(Form):
     use = BooleanField(label='Import')
     name = CharField(max_length=50)
     url = URLField()
     tags = CharField(max_length=50, required=False)
     category = ChoiceField(choices=categories)
 def test_choicefield_choices_default(self):
     f = ChoiceField()
     self.assertEqual(f.choices, [])
Exemple #24
0
class SearchForm(Form):
    SEARCH_CHOICES = (('A', 'everything'), ('B', 'titles'), ('C', 'tags'),
                      ('D', 'composer'), ('E', 'first line lyrics'))
    search = CharField(max_length=200)
    options = ChoiceField(SEARCH_CHOICES)
Exemple #25
0
 def __init__(self, *args, **kwargs):
     super(LdapAuthenticationForm, self).__init__(*args, **kwargs)
     self.fields['server'] = ChoiceField(choices=get_server_choices())
     self.error_messages['invalid_login'] = _t(
         "Invalid username or password, or your LDAP groups not allowed")
Exemple #26
0
class BlockListGetForm(Form):
    """
    A form to validate query parameters in the block list retrieval endpoint
    """
    username = CharField(
        required=True
    )  # TODO return all blocks if user is not specified by requesting staff user
    usage_key = CharField(required=True)
    requested_fields = MultiValueField(required=False)
    student_view_data = MultiValueField(required=False)
    block_counts = MultiValueField(required=False)
    depth = CharField(required=False)
    nav_depth = IntegerField(required=False, min_value=0)
    return_type = ChoiceField(
        required=False,
        choices=[(choice, choice) for choice in ['dict', 'list']],
    )

    def clean_requested_fields(self):
        """
        Return a set of `requested_fields`, merged with defaults of `type`
        and `display_name`
        """
        requested_fields = self.cleaned_data['requested_fields']

        # add default requested_fields
        return (requested_fields or set()) | {'type', 'display_name'}

    def clean_depth(self):
        """
        Get the appropriate depth.  No provided value will be treated as a
        depth of 0, while a value of "all" will be treated as unlimited depth.
        """
        value = self.cleaned_data['depth']
        if not value:
            return 0
        elif value == "all":
            return None
        try:
            return int(value)
        except ValueError:
            raise ValidationError(
                "'{}' is not a valid depth value.".format(value))

    def clean_usage_key(self):
        """
        Ensure a valid `usage_key` was provided.
        """
        usage_key = self.cleaned_data['usage_key']

        try:
            usage_key = UsageKey.from_string(usage_key)
            usage_key = usage_key.replace(
                course_key=modulestore().fill_in_run(usage_key.course_key))
        except InvalidKeyError:
            raise ValidationError("'{}' is not a valid usage key.".format(
                unicode(usage_key)))

        return usage_key

    def clean_return_type(self):
        """
        Return valid 'return_type' or default value of 'dict'
        """
        return self.cleaned_data['return_type'] or 'dict'

    def clean_requested_user(self, cleaned_data, course_key):
        """
        Validates and returns the requested_user, while checking permissions.
        """
        requested_username = cleaned_data.get('username', '')
        requesting_user = self.initial['requesting_user']

        if requesting_user.username.lower() == requested_username.lower():
            requested_user = requesting_user
        else:
            # the requesting user is trying to access another user's view
            # verify requesting user can access another user's blocks
            if not can_access_other_users_blocks(requesting_user, course_key):
                raise PermissionDenied(
                    "'{requesting_username}' does not have permission to access view for '{requested_username}'."
                    .format(requesting_username=requesting_user.username,
                            requested_username=requested_username))

            # update requested user object
            try:
                requested_user = User.objects.get(username=requested_username)
            except User.DoesNotExist:
                raise Http404(
                    "Requested user '{username}' does not exist.".format(
                        username=requested_username))

        # verify whether the requested user's blocks can be accessed
        if not can_access_users_blocks(requested_user, course_key):
            raise PermissionDenied(
                "Course blocks for '{requested_username}' cannot be accessed.".
                format(requested_username=requested_username))

        return requested_user

    def clean(self):
        """
        Return cleaned data, including additional requested fields.
        """
        cleaned_data = super(BlockListGetForm, self).clean()

        # add additional requested_fields that are specified as separate parameters, if they were requested
        additional_requested_fields = [
            'student_view_data',
            'block_counts',
            'nav_depth',
        ]
        for additional_field in additional_requested_fields:
            field_value = cleaned_data.get(additional_field)
            if field_value or field_value == 0:  # allow 0 as a requested value
                cleaned_data['requested_fields'].add(additional_field)

        usage_key = cleaned_data.get('usage_key')
        if not usage_key:
            return

        cleaned_data['user'] = self.clean_requested_user(
            cleaned_data, usage_key.course_key)
        return cleaned_data
Exemple #27
0
class EvaluatorForm(Form):
    rating = ChoiceField(choices=((None, ''), ('1', '1'), ('2', '2'),
                                  ('3', '3'), ('4', '4'), ('5', '5'), ('6',
                                                                       '6')),
                         required=True)
    notes = CharField(widget=Textarea())
Exemple #28
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
Exemple #29
0
class RepositoryRoleForm(Form):
    name = CharField(max_length=256, disabled=True)
    role = ChoiceField(choices=RepositoryRoleLevel.choices)
Exemple #30
0
 def __init__(self, *args, **kwargs):
     super(LdapUserCreationForm, self).__init__(*args, **kwargs)
     self.fields['server'] = ChoiceField(choices=get_server_choices())
class OrderForm(Form):

    numero = ChoiceField(label="Items a mostrar", choices=numero)
    ordenar_por = ChoiceField(label="Ordenar Por", choices=orden)
    orden = ChoiceField(label="Ascendente", choices=ascendente)
    def test_choicefield_callable(self):
        def choices():
            return [("J", "John"), ("P", "Paul")]

        f = ChoiceField(choices=choices)
        self.assertEqual("J", f.clean("J"))
Exemple #33
0
class DemographicForm(Form):
    financialaid = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')),
                               required=True)
    financialaidreason = CharField()
    financialaward = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')),
                                 required=True)
    financialawardlist = CharField()
    economicallydisadvantaged = ChoiceField(choices=(('1', 'No'), ('2',
                                                                   'Yes')),
                                            required=True)
    income = ChoiceField(
        choices=(('1', '$15,000 or under'), ('2', '$15,001 - $25,000'),
                 ('3', '$25,001 - $35,000'), ('4', '35,001 - $55,000'),
                 ('5', '$55,001 - $75,000'), ('6', '$75,001 - $95,000'),
                 ('7', '$95,001 - $125,000'), ('8', '$125,001 - $160,000'),
                 ('9', '$160,001 and above')),
        required=True)
    headofhousehold = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')),
                                  required=True)
    dependents = IntegerField()
    parent = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')), required=True)
    children = IntegerField()
    immigrant = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')), required=True)
    immigrationcountry = CharField()
    immigrationdate = CharField()
    motherimmigrant = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')),
                                  required=True)
    motherimmigrationcountry = CharField()
    motherimmigrationdate = CharField()
    mothereducation = CharField()
    fatherimmigrant = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')),
                                  required=True)
    fatherimmigrationcountry = CharField()
    fatherimmigrationdate = CharField()
    fathereducation = CharField()
    ab540 = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')), required=True)
    firstgencollege = ChoiceField(choices=(('1', 'No'), ('2', 'Yes')),
                                  required=True)
    primaryhomelanguage = CharField()
 def test_choicefield_3(self):
     f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
     self.assertEqual('J', f.clean('J'))
     msg = "'Select a valid choice. John is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('John')
 class ChoiceFieldForm(Form):
     choicefield = ChoiceField(choices=choices_as_callable)
 def test_choicefield_callable(self):
     def choices():
         return [('J', 'John'), ('P', 'Paul')]
     f = ChoiceField(choices=choices)
     self.assertEqual('J', f.clean('J'))
Exemple #37
0
 def __init__(self, *args, **kwargs):
     super(ServiceSettingsAdminForm, self).__init__(*args, **kwargs)
     self.fields['type'] = ChoiceField(choices=SupportedServices.get_choices(),
                                       widget=RadioSelect)