Пример #1
0
    def get_results(self, request, term, page, context):
        term = term.lower()
        start = (page - 1) * 10
        end = page * 10

        User = get_user_model()

        uids = self.group.members

        # if this is a Project, add all users of its parent Group as well
        # (disabled for now as it leads to a lot of confusion)
        # if self.group.parent:
        #    uids = list(set(uids + self.group.parent.members))

        terms = term.strip().lower().split(' ')
        q = get_user_query_filter_for_search_terms(terms)

        user_qs = filter_active_users(
            User.objects.filter(id__in=uids).filter(q))

        count = user_qs.count()
        if count < start:
            raise Http404
        has_more = count > end

        users = user_qs.all()[start:end]
        #results = get_user_choices(users)
        results = get_user_select2_pills(users)

        return (NO_ERR_RESP, has_more, results)
    def get_formfield_kwargs(self):
        if settings.COSINNUS_MANAGED_TAG_DYNAMIC_USER_FIELD_FILTER_ON_TAG_SLUG:
            data_url = reverse(
                'cosinnus:select2:managed-tag-members',
                kwargs={
                    'tag_slug':
                    settings.
                    COSINNUS_MANAGED_TAG_DYNAMIC_USER_FIELD_FILTER_ON_TAG_SLUG
                })
        else:
            data_url = reverse('cosinnus:select2:all-members')

        if self._dynamic_field_initial:
            initial_user_ids = get_user_model().objects.filter(
                id__in=self._dynamic_field_initial)
        else:
            initial_user_ids = get_user_model().objects.none()
        preresults = get_user_select2_pills(initial_user_ids, text_only=False)
        new_initial = [key for key, val in preresults]
        self._new_initial_after_formfield_creation = new_initial
        return {
            'data_url':
            data_url,
            'widget':
            HeavySelect2MultipleWidget(data_url=data_url, choices=preresults),
            'choices':
            preresults,
            'initial':
            new_initial
        }
Пример #3
0
 def __init__(self, *args, **kwargs):
     super(CustomWriteForm, self).__init__(*args, **kwargs)
     
     # retrieve the attached objects ids to select them in the update view
     users = []
     initial_users = kwargs['initial'].get('recipients', None)
     preresults = []
     use_ids = False
     recipient_list = []
     
     if initial_users:
         recipient_list = initial_users.split(', ')
         # delete the initial data or our select2 field initials will be overwritten by django
         if 'recipients' in kwargs['initial']:
             del kwargs['initial']['recipients']
         if 'recipients' in self.initial:
             del self.initial['recipients']
     elif 'data' in kwargs and kwargs['data'].getlist('recipients'):
         recipient_list = kwargs['data'].getlist('recipients')
         use_ids = True
         
     if recipient_list:
         ids = self.fields['recipients'].get_ids_for_value(recipient_list, intify=use_ids)
         user_tokens = ids.get('user', [])
         group_tokens = ids.get('group', [])
             
         if use_ids:
             # restrict writing to the forum group
             forum_slug = getattr(settings, 'NEWW_FORUM_GROUP_SLUG', None)
             if forum_slug:
                 try:
                     forum_group_id = CosinnusGroup.objects.get_cached(slugs=forum_slug).id
                     if forum_group_id in group_tokens and not check_user_superuser(kwargs['sender']):
                         self.restricted_recipient_flag = True
                 except CosinnusGroup.DoesNotExist:
                     pass
             users = get_user_model().objects.filter(id__in=user_tokens)
             groups = CosinnusGroup.objects.get_cached(pks=group_tokens)
         else:
             # restrict writing to the forum group
             if getattr(settings, 'NEWW_FORUM_GROUP_SLUG', None) and getattr(settings, 'NEWW_FORUM_GROUP_SLUG') in group_tokens:
                 self.restricted_recipient_flag = True
             users = get_user_model().objects.filter(username__in=user_tokens)
             groups = CosinnusGroup.objects.get_cached(slugs=group_tokens)
         # save away for later
         self.targetted_groups = groups
         
         preresults = get_user_select2_pills(users, text_only=False)
         preresults.extend(get_group_select2_pills(groups, text_only=False))
             
     # we need to cheat our way around select2's annoying way of clearing initial data fields
     self.fields['recipients'].choices = preresults
     self.fields['recipients'].initial = [key for key,val in preresults]
     self.initial['recipients'] = self.fields['recipients'].initial
Пример #4
0
    def get_results(self, request, term, page, context):
        start = (page - 1) * 10
        end = page * 10

        User = get_user_model()

        terms = term.strip().lower().split(' ')

        user_qs = User.objects.all()
        user_qs = self.filter_user_qs(user_qs, terms)

        count = user_qs.count()
        if count < start:
            raise Http404
        has_more = count > end

        users = user_qs.all()[start:end]
        #results = get_user_choices(users)
        results = get_user_select2_pills(users)

        return (NO_ERR_RESP, has_more, results)
Пример #5
0
    def __init__(self, *args, **kwargs):

        # note: super(_EventForm), not _ConferenceEventBaseForm
        super(_EventForm, self).__init__(*args, **kwargs)

        # init select2 presenters field
        if 'presenters' in self.fields:
            data_url = reverse('cosinnus:select2:all-members')
            self.fields['presenters'] = UserSelect2MultipleChoiceField(
                label=_("Presenters"),
                help_text='',
                required=False,
                data_url=data_url)

            if self.instance.pk:
                # choices and initial must be set so pre-existing form fields can be prepopulated
                preresults = get_user_select2_pills(
                    self.instance.presenters.all(), text_only=True)
                self.fields['presenters'].choices = preresults
                self.fields['presenters'].initial = [
                    key for key, __ in preresults
                ]
                self.initial['presenters'] = self.fields['presenters'].initial
Пример #6
0
    def get_results(self, request, term, page, context):
        start = (page - 1) * 10
        end = page * 10

        User = get_user_model()

        terms = term.strip().lower().split(' ')
        q = get_user_query_filter_for_search_terms(terms)

        user_qs = filter_active_users(
            User.objects.filter(
                id__in=CosinnusPortal.get_current().members).filter(q))

        count = user_qs.count()
        if count < start:
            raise Http404
        has_more = count > end

        users = user_qs.all()[start:end]
        #results = get_user_choices(users)
        results = get_user_select2_pills(users)

        return (NO_ERR_RESP, has_more, results)
Пример #7
0
    def __init__(self, *args, **kwargs):
        """ Initialize and populate the select2 tags field
        """
        super(BaseTagObjectForm, self).__init__(*args, **kwargs)

        # needs to be initialized here because using reverser_lazy() at model instantiation time causes problems
        self.fields['tags'] = TagSelect2Field(
            required=False, data_url=reverse_lazy('cosinnus:select2:tags'))
        # inherit tags from group for new TaggableObjects
        preresults = []
        if self.instance.pk:
            preresults = self.instance.tags.values_list('name', 'name').all()
        elif self.group:
            preresults = self.group.media_tag.tags.values_list('name',
                                                               'name').all()

        if preresults:
            self.fields['tags'].choices = preresults
            self.fields['tags'].initial = [
                key for key, val in preresults
            ]  #[tag.name for tag in self.instance.tags.all()]
            self.initial['tags'] = self.fields['tags'].initial

        # if no media tag data was supplied the object was created directly and not through a frontend form
        # we then manually inherit the group's media_tag topics by adding them to the data
        # (usually they would have been added into the form's initial data)
        if self.data and not any(
            [key.startswith('media_tag-') for key in list(self.data.keys())]
        ) and self.group and self.group.media_tag and self.group.media_tag.topics:
            self.data._mutable = True
            self.data.setlist('media_tag-topics',
                              self.group.media_tag.topics.split(','))

        if self.group and not self.instance.pk:
            # for new TaggableObjects (not groups), set the default visibility corresponding to the group's public status
            self.fields[
                'visibility'].initial = get_inherited_visibility_from_group(
                    self.group)

        if self.group:
            data_url = group_aware_reverse('cosinnus:select2:group-members',
                                           kwargs={'group': self.group})
        else:
            data_url = reverse('cosinnus:select2:all-members')

        # override the default persons field with select2
        #self.fields['persons'] = HeavySelect2MultipleChoiceField(label=_("Persons"), help_text='', required=False, data_url=data_url)
        self.fields['persons'] = UserSelect2MultipleChoiceField(
            label=_("Persons"),
            help_text='',
            required=False,
            data_url=data_url)

        if self.instance.pk:
            # choices and initial must be set so pre-existing form fields can be prepopulated
            preresults = get_user_select2_pills(self.instance.persons.all(),
                                                text_only=False)
            self.fields['persons'].choices = preresults
            self.fields['persons'].initial = [key for key, val in preresults]
            self.initial['persons'] = self.fields['persons'].initial

        if self.group and self.group.media_tag_id:
            group_media_tag = self.group.media_tag
            if group_media_tag and group_media_tag is not self.instance:
                # We must only take data from the group's media tag iff we are
                # working on a TaggableObjectModel, not on a group
                opts = self._meta

                # 1. Use all the data from the group's media tag
                # 2. Use the explicitly defined initial data (self.initial) and
                #    override the data from the group media tag
                # 3. Set the combined data as new initial data
                group_data = forms.model_to_dict(group_media_tag, opts.fields,
                                                 opts.exclude)
                group_data.update(self.initial)

                old_initial = self.initial
                self.initial = group_data

                # the default visibility corresponds to group's public setting
                if 'visibility' in old_initial:
                    self.initial['visibility'] = old_initial['visibility']
                else:
                    self.initial[
                        'visibility'] = get_inherited_visibility_from_group(
                            self.group)

        if (self.user and self.instance.pk
                and self.instance.likers.filter(id=self.user.id).exists()):
            self.fields['like'].initial = True

        # use select2 widgets for m2m fields
        for field in [
                self.fields['text_topics'],
        ]:
            if type(field.widget) is SelectMultiple:
                field.widget = Select2MultipleWidget(choices=field.choices)

        # since the widget currently ignores the allowClear setting we have
        # to use this hack to remove the clear-button
        self.fields['visibility'].widget.is_required = True

        # save BBB room
        if self.instance.pk and self.instance.bbb_room:
            self.initial['bbb_room'] = self.instance.bbb_room
Пример #8
0
 def get_select2_pills(self, items, text_only=False):
     return get_user_select2_pills(items, text_only=text_only)