Esempio n. 1
0
    def __init__(self, descriptions, envts, cics, **kwargs):
        super(CIForm, self).__init__(**kwargs)
        iterator = ModelChoiceIterator(self.fields['description'])
        choices = [iterator.choice(obj) for obj in descriptions]
        choices.append(("", self.fields['description'].empty_label))
        self.fields['description'].choices = choices

        iterator = ModelChoiceIterator(self.fields['environments'])
        choices = [iterator.choice(obj) for obj in envts]
        self.fields['environments'].choices = choices

        iterator = ModelChoiceIterator(self.fields['instanciates'])
        choices = [iterator.choice(obj) for obj in cics]
        choices.append(("", self.fields['instanciates'].empty_label))
        self.fields['instanciates'].choices = choices
Esempio n. 2
0
File: forms.py Progetto: e-n-0/site
    def __init__(self, *args, **kwargs):
        edition = kwargs.pop('edition')
        kwargs.pop('complete')
        super().__init__(*args, **kwargs)

        # Overwrite assignation_semifinal_wishes with our custom over-engineered field
        self.fields['assignation_semifinal_wishes'] = EventWishChoiceField(
            queryset=(
                contest.models.Event.objects.select_related('center').filter(
                    edition=edition,
                    type=contest.models.Event.Type.semifinal.value)),
            min_choices=0,
            max_choices=settings.PROLOGIN_SEMIFINAL_MAX_WISH_COUNT,
            label=_("Regional event center wishes"),
            help_text=
            _("This is where you would like to seat the regional events if you "
              "are selected. Choose at least one and up to three wishes, in "
              "order of preference. Most of the time, we are able to satisfy "
              "your first choice."))
        if self.instance:
            # BEGIN f*****g hack not to display full queryset
            school_field = self.fields['school']
            it = ModelChoiceIterator(school_field)
            if self.instance.school:
                it.queryset = it.queryset.filter(pk=self.instance.school.pk)
            else:
                it.queryset = it.queryset.none()
            school_field.choices = list(it)
            # END f*****g hack
            # FIXME: figure why we have to do the ordering manually
            self.initial['assignation_semifinal_wishes'] = list(
                self.instance.assignation_semifinal_wishes.order_by(
                    'eventwish__order').values_list('pk', flat=True))
        self._edition = edition
Esempio n. 3
0
 def __init__(self, *args, **kwargs):
     super(ModelMultipleChoiceFieldWithTitle,
           self).__init__(*args, **kwargs)
     iterator = ModelChoiceIterator(self)
     choices = [iterator.choice(obj) for obj in kwargs['queryset'].all()]
     choices.append(("", self.empty_label))
     self.choices = choices
Esempio n. 4
0
    def get_data(self, queryset, page=None, page_limit=None):
        field = self.get_field()
        formfield = field.formfield()
        total_count = None
        if page is not None and page_limit is not None:
            total_count = queryset.count()
            offset = (page - 1) * page_limit
            end = offset + page_limit
            queryset = queryset[offset:end]
        else:
            offset = None

        formfield.queryset = queryset
        iterator = ModelChoiceIterator(formfield)

        if offset is None:
            total_count = len(iterator)
            more = False
        else:
            paged_count = offset + len(iterator)
            more = bool(paged_count < total_count)

        data = {
            'total': total_count,
            'more': more,
            'results': [],
        }
        for value, label in iterator:
            if value is u'':
                continue
            data['results'].append({
                'id': value,
                'text': label,
            })
        return data
Esempio n. 5
0
def html_selector(model,
                  id,
                  default=0,
                  placeholder="",
                  attrs={}):  # @ReservedAssignment
    '''
    Returns an HTML string for a model selector.
    :param model:        The model to provide a selector widget for
    :param id:           The id of the widget
    :param default:      The default selection supplied (widget's initial condition)
    :param placeholder:  The text that forms the background of the empty widget
    :param attrs:        Any extra attributes to provide the widget with
    '''
    url = reverse_lazy('autocomplete_all',
                       kwargs={
                           "model": model.__name__,
                           "field_name": model.selector_field
                       })
    field = ModelMultipleChoiceField(model.objects.all())

    widget = autocomplete.ModelSelect2Multiple(url=url,
                                               attrs={
                                                   **attrs, "class":
                                                   "multi_selector",
                                                   "id": id,
                                                   "data-placeholder":
                                                   placeholder,
                                                   "data-theme": "bootstrap"
                                               })
    widget.choices = ModelChoiceIterator(field)

    return widget.render(model.__name__, default)
Esempio n. 6
0
    def optgroups(self, name, value, attrs=None):
        """Return only selected options and set QuerySet from `ModelChoicesIterator`."""
        default = (None, [], 0)
        groups = [default]
        has_selected = False
        selected_choices = {str(v) for v in value}
        if not self.is_required and not self.allow_multiple_selected:
            default[1].append(self.create_option(name, '', '', False, 0))
        if not isinstance(self.choices, ModelChoiceIterator):
            modelchoise_query = self.model.objects.all()
            modelchoise_field = ModelChoiceField(modelchoise_query)
            modelchoise_iter = ModelChoiceIterator(modelchoise_field)
            self.choices = modelchoise_iter
        selected_choices = {
            c
            for c in selected_choices
            if c not in self.choices.field.empty_values
        }
        field_name = self.choices.field.to_field_name or 'pk'
        query = Q(**{'%s__in' % field_name: selected_choices})
        for obj in self.choices.queryset.filter(query):
            option_value = self.choices.choice(obj)[0]
            option_label = self.label_from_instance(obj)

            selected = (str(option_value) in value
                        and (has_selected is False
                             or self.allow_multiple_selected))
            if selected is True and has_selected is False:
                has_selected = True
            index = len(default[1])
            subgroup = default[1]
            subgroup.append(
                self.create_option(name, option_value, option_label,
                                   selected_choices, index))
        return groups
Esempio n. 7
0
 def limit_method_fields(self):
     basket = self.basket  # type: shoop.front.basket.objects.BaseBasket
     for field_name, methods in (
             ("shipping_method", basket.get_available_shipping_methods()),
             ("payment_method", basket.get_available_payment_methods()),
     ):
         field = self.fields[field_name]
         field.basket = self.basket
         mci = ModelChoiceIterator(field)
         field.choices = [mci.choice(obj) for obj in methods]
         if field.choices:
             field.initial = field.choices[0][0]
Esempio n. 8
0
    def _get_choices(self):
        # If self._choices is set, then somebody must have manually set
        # the property self.choices. In this case, just return self._choices.
        if hasattr(self, "_choices"):
            return self._choices

        # Otherwise, execute the QuerySet in self.queryset to determine the
        # choices dynamically. Return a fresh ModelChoiceIterator that has not been
        # consumed. Note that we"re instantiating a new ModelChoiceIterator *each*
        # time _get_choices() is called (and, thus, each time self.choices is
        # accessed) so that we can ensure the QuerySet has not been consumed. This
        # construct might look complicated but it allows for lazy evaluation of
        # the queryset.
        return ModelChoiceIterator(self)
Esempio n. 9
0
    def get_data(self, queryset, page=None, page_limit=None):
        field, model_cls = self.get_field_and_model()

        # Check for the existences of a callable %s_queryset method on the
        # model class and use it to filter the Select2 queryset.
        #
        # This is useful for model inheritance where the limit_choices_to can
        # not easily be overriden in child classes.
        model_queryset_method = '%s_queryset' % field.name
        if callable(getattr(model_cls, model_queryset_method, None)):
            queryset = getattr(model_cls, model_queryset_method)(queryset)

        formfield = field.formfield()
        total_count = None
        if page is not None and page_limit is not None:
            total_count = queryset.count()
            offset = (page - 1) * page_limit
            end = offset + page_limit
            queryset = queryset[offset:end]
        else:
            offset = None

        formfield.queryset = queryset
        iterator = ModelChoiceIterator(formfield)

        if offset is None:
            total_count = len(iterator)
            more = False
        else:
            paged_count = offset + len(iterator)
            more = bool(paged_count < total_count)

        data = {
            'total': total_count,
            'more': more,
            'results': [],
        }
        for value, label in iterator:
            if value is u'':
                continue
            data['results'].append({
                'id': value,
                'text': label,
            })
        return data
Esempio n. 10
0
    def __init__(self, cics, **kwargs):
        super(ReinitModelForm, self).__init__(**kwargs)

        iterator = ModelChoiceIterator(self.fields['instanciates'])
        choices = [iterator.choice(obj) for obj in cics]
        choices.append(("", self.fields['instanciates'].empty_label))
        self.fields['instanciates'].choices = choices

        if self.instance:
            # Stupid: self.instance can be overridden by a field named instance... So we store it inside another field (with a forbidden name)
            self.mage_instance = self.instance

            for field_instance in self.instance.rel_target_set.all():
                if field_instance.field.max_cardinality > 1:
                    continue
                self.fields[field_instance.field.
                            name].initial = field_instance.target_id

            for field_instance in self.instance.field_set.all():
                self.fields[
                    field_instance.field.name].initial = field_instance.value
Esempio n. 11
0
    def test_normal_select_widget_without_groups(self):
        """
        Using it like a select widget
        """
        vat = Vat.objects.create(code="1", name="standard", rate="20")
        mock_field = mock.Mock()
        mock_field.empty_label = ""
        mock_field.label_from_instance = lambda o: str(o)
        mock_field.prepare_value = lambda o: o.pk
        mock_field.queryset = Vat.objects.all()
        it = ModelChoiceIterator(mock_field)
        it = iter(it)
        widget = SelectWithDataAttr(choices=it)
        # ctx = widget.get_context("vat", vat.pk, {})
        widget_html = widget.render("vat", vat.pk)
        self.assertHTMLEqual(
            widget_html, f"""<select name="vat">
                <option value=""></option>

                <option value="{vat.pk}" selected>1 - standard - 20.00%</option>

            </select>""")
Esempio n. 12
0
    def test_with_data_option_attrs_without_model_attrs(self):
        """
        Check that data-option-attrs works without model attrs.
        This is pointless but need to check it doesn't break the widget.
        """
        vat = Vat.objects.create(code="1", name="standard", rate="20")
        mock_field = mock.Mock()
        mock_field.empty_label = ""
        mock_field.label_from_instance = lambda o: str(o)
        mock_field.prepare_value = lambda o: o.pk
        mock_field.queryset = Vat.objects.all()
        it = ModelChoiceIterator(mock_field)
        it = iter(it)
        widget = SelectWithDataAttr(choices=it,
                                    attrs={"data-option-attrs": ["rate"]})
        # ctx = widget.get_context("vat", vat.pk, {})
        widget_html = widget.render("vat", vat.pk)
        self.assertHTMLEqual(
            widget_html, f"""<select name="vat">
            <option value=""></option>

            <option value="{vat.pk}" selected>1 - standard - 20.00%</option>

            </select>""")
Esempio n. 13
0
 def __init__(self, cics, **kwargs):
     super(MiniModelForm, self).__init__(**kwargs)
     iterator = ModelChoiceIterator(self.fields['_instanciates'])
     choices = [iterator.choice(obj) for obj in cics]
     choices.append(("", self.fields['_instanciates'].empty_label))
     self.fields['_instanciates'].choices = choices
Esempio n. 14
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     queryset = Organisation.objects.filter(is_active=True)
     iterator = ModelChoiceIterator(field=self.fields['organisation'])
     iterator.queryset = queryset
     self.fields['organisation'].choices = iterator