Exemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        """ init(me). """

        super(ManageSubscriptionForm, self).__init__(*args, **kwargs)

        folders_queryset = self.instance.user.folders_tree
        preferences = self.instance.user.preferences

        if preferences.selector.subscriptions_in_multiple_folders:
            self.fields['folders'] = OnlyNameMultipleChoiceField(
                queryset=folders_queryset,
                required=False,
                label=_(u'Folders'),
                widget=Select2MultipleWidget(),
                initial=self.instance.folders.all())
            # no empty_label here.

        else:
            self.fields['folders'] = OnlyNameChoiceField(
                queryset=folders_queryset,
                required=False,
                widget=Select2Widget(),
                label=_(u'Folder'),
                empty_label=_(u'(None)'))

            try:
                self.fields['folders'].initial = self.instance.folders.all()[0]

            except IndexError:
                # Subscription is not in any folder yet.
                pass
Exemplo n.º 2
0
class AsignUserToEventForm(forms.Form):
    event_id = forms.CharField(widget=forms.HiddenInput())
    event_name = forms.CharField(required=False)
    users = forms.MultipleChoiceField(widget=Select2MultipleWidget(),
                                      required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if not hasattr(settings, 'COSINNUS_CONFERENCE_PARTICIPATION_OPTIONS'):
            del self.fields['application_options']

        for field in list(self.fields.values()):
            if type(field.widget) is SelectMultiple:
                field.widget = Select2MultipleWidget(choices=field.choices)
Exemplo n.º 4
0
 class Meta:
     model=Topic
     fields=['title', 'header', 'content', 'tag']
     widgets = {
         'tag': Select2MultipleWidget(select2_options={
                             'placeholder':'Type and Choice Tags',
                             'minimumResultsForSearch': 10,
                             'closeOnSelect': False,
                             }),
     }
Exemplo n.º 5
0
 class Meta:
     model = Game
     exclude = ['owner', 'date_published']
     widgets = {
         'description': Textarea(attrs={
             'cols': 100,
             'rows': 5
         }),
         'tags': Select2MultipleWidget(),
     }
Exemplo n.º 6
0
class groupAddForm(forms.Form):
    """
  Group Add Form
  """
    title = "Add Group & Commands"
    gname = forms.CharField(label='Group Name', max_length=255)
    display_name = forms.CharField(label='Display Name', max_length=255)
    mail_pdl = forms.EmailField(label='Group PDL')

    cmd_aliases = forms.ModelMultipleChoiceField(
        widget=Select2MultipleWidget(select2_options={'width': 'resolve'}),
        label='Command Alias',
        queryset=CmdAliasModel.objects.filter(gid__isnull=True))

    #Group Name field level validations
    def clean_grpname(self):
        group_name = self.cleaned_data.get('gname')
        if group_name.find(' ') > -1:
            raise forms.ValidationError("Group Name cannot be with spaces")

        if not re.match(r'^[A-Za-z0-9_]+$', group_name):
            raise forms.ValidationError(group_name +
                                        " should be in alphanumeric string")

        return group_name

    #DisPlay Name Validations
    def clean_display_name(self):
        display_name = self.cleaned_data.get('display_name')
        if display_name[0] == ' ':
            raise forms.ValidationError(display_name +
                                        " cannot start with spaces")
        return display_name

    #Clean Mail PDL
    def clean_mail_pdl(self):
        mailadd = self.cleaned_data.get('mail_pdl')
        domain, provider = mailadd.split('@')
        if not provider == 'rpxcorp.com':
            raise forms.ValidationError(
                "Mail address required to be RPX Corporation domain")
        return mailadd

    #Form Level Validations
    def clean(self):
        cleaned_data = self.cleaned_data
        gname = cleaned_data.get('gname')
        groupmodel_data = GroupModel.objects.filter(gname=gname)
        if len(groupmodel_data) > 0:
            raise forms.ValidationError(gname + " Already Exists")
        return cleaned_data
Exemplo n.º 7
0
 def __init__(self, instance, *args, **kwargs):
     if 'request' in kwargs:
         self.request = kwargs.pop('request')
     super(CosinnusBaseGroupForm, self).__init__(instance=instance, *args, **kwargs)
         
     self.fields['related_groups'] = HeavyModelSelect2MultipleChoiceField(
              required=False, 
              data_url=reverse('cosinnus:select2:groups') + ('?except='+str(instance.pk) if instance else ''),
              queryset=get_cosinnus_group_model().objects.filter(portal_id=CosinnusPortal.get_current().id),
              initial=[] if not instance else [rel_group.pk for rel_group in instance.related_groups.all()],
          )
     if settings.COSINNUS_GROUP_DASHBOARD_EMBED_HTML_FIELD_ENABLED and not is_superuser(self.request.user):
         self.fields['embedded_dashboard_html'].disabled = True
     if not settings.COSINNUS_ENABLE_SDGS:
         del self.fields['sdgs']
     
     # use select2 widgets for m2m fields
     for field in list(self.fields.values()):
         if type(field.widget) is SelectMultiple:
             field.widget = Select2MultipleWidget(choices=field.choices)
Exemplo n.º 8
0
    def __init__(self, instance, *args, **kwargs):
        if 'request' in kwargs:
            self.request = kwargs.pop('request')
        super(CosinnusBaseGroupForm, self).__init__(instance=instance,
                                                    *args,
                                                    **kwargs)

        self.fields['related_groups'] = HeavyModelSelect2MultipleChoiceField(
            required=False,
            data_url=reverse('cosinnus:select2:groups') +
            ('?except=' + str(instance.pk) if instance else ''),
            queryset=get_cosinnus_group_model().objects.filter(
                portal_id=CosinnusPortal.get_current().id),
            initial=[] if not instance else
            [rel_group.pk for rel_group in instance.related_groups.all()],
        )

        # use select2 widgets for m2m fields
        for field in list(self.fields.values()):
            if type(field.widget) is SelectMultiple:
                field.widget = Select2MultipleWidget(choices=field.choices)
Exemplo n.º 9
0
    def __init__(self, *args, **kwargs):
        if 'participation_management' in kwargs:
            self.participation_management = kwargs.pop(
                'participation_management')
        super().__init__(*args, **kwargs)
        self.fields['options'] = forms.MultipleChoiceField(
            choices=self.get_options(), required=False)

        for field in list(self.fields.values()):
            if type(field.widget) is SelectMultiple:
                field.widget = Select2MultipleWidget(choices=field.choices)

        if (not hasattr(self, 'participation_management') or
            (not self.participation_management.application_conditions and
             not self.participation_management.application_conditions_upload)
                or self.instance.id):
            del self.fields['conditions_accepted']
        if (not hasattr(self, 'participation_management')
                or not self.participation_management.application_options):
            del self.fields['options']
        if (not hasattr(self, 'participation_management') or
                not self.participation_management.information_field_enabled):
            del self.fields['information']
        else:
            self.fields['information'].required = True

        if ('information' in self.fields
                and hasattr(self, 'participation_management') and
                self.participation_management.information_field_initial_text):
            self.fields[
                'information'].initial = self.participation_management.information_field_initial_text

        # exclude some optional fields for this portal
        for field_name in settings.COSINNUS_CONFERENCE_APPLICATION_FORM_HIDDEN_FIELDS:
            if field_name in self.fields:
                del self.fields[field_name]
Exemplo n.º 10
0
class SpeechForm(forms.ModelForm, CleanAudioMixin):
    audio_filename = forms.CharField(widget=forms.HiddenInput, required=False)
    text = SpeechTextField(required=False, label=verbose_name(Speech, 'text'))
    speaker = SpeakerField(label=verbose_name(Speech, 'speaker'))
    section = SectionField(label=verbose_name(Speech, 'section'))

    type = forms.ChoiceField(
        label=verbose_name(Speech, 'type'),
        choices=Speech._meta.get_field('type').choices,
        widget=forms.HiddenInput, required=False,
        )

    start_date = forms.DateField(
        label=verbose_name(Speech, 'start_date'),
        widget=DatePickerWidget,
        required=False,
        localize=True,
        )
    start_time = forms.TimeField(
        input_formats=['%H:%M', '%H:%M:%S'],
        label=verbose_name(Speech, 'start_time'),
        widget=TimePickerWidget,
        required=False,
        )
    end_date = forms.DateField(
        label=verbose_name(Speech, 'end_date'),
        widget=DatePickerWidget,
        required=False,
        localize=True,
        )
    end_time = forms.TimeField(
        input_formats=['%H:%M', '%H:%M:%S'],
        label=verbose_name(Speech, 'end_time'),
        widget=TimePickerWidget,
        required=False,
        )
    # tags = TagField()
    tags = forms.ModelMultipleChoiceField(
        queryset=Tag.objects.all(),
        label=verbose_name(Speech, 'tags'),
        widget=Select2MultipleWidget(
            select2_options={'placeholder': _('Choose tags'),
                             'width': 'resolve'}),
        required=False,
        )

    def clean(self):
        cleaned_data = self.cleaned_data

        # Temporary fix - see issue #340 (
        if not cleaned_data.get('type'):
            cleaned_data['type'] = ('speech' if cleaned_data.get('speaker')
                                    else 'narrative')

        if 'audio_filename' in cleaned_data and cleaned_data['audio_filename']:
            filename = cleaned_data['audio_filename']
            self.cleaned_data['audio'] = filename

        if not cleaned_data.get('text') and not cleaned_data.get('audio'):
            raise forms.ValidationError(
                _('You must provide either text or some audio'))

        # If we have text but no speaker, then this should become a
        # <narrative> element in the Akoma Ntoso, which can't contain
        # <p> elements, so we should replace any in the middle with
        # <br /> and get rid of the ones round the outside.
        if 'text' in cleaned_data and not cleaned_data.get('speaker'):
            text = cleaned_data['text']
            text = re.sub(r'</p>\n\n<p>', '<br />\n', text)
            text = re.sub(r'</?p>', '', text)
            cleaned_data['text'] = text

        return cleaned_data

    def clean_start_time(self):
        if (self.cleaned_data['start_time'] and
                not self.cleaned_data.get('start_date')):
            raise forms.ValidationError(
                _('If you provide a start time you must give a start date too')
                )
        return self.cleaned_data['start_time']

    def clean_end_time(self):
        if self.cleaned_data['end_time'] and not self.cleaned_data['end_date']:
            raise forms.ValidationError(
                _('If you provide an end time you must give an end date too'))
        return self.cleaned_data['end_time']

    class Meta:
        model = Speech
        widgets = {
            'audio': AudioFileInput,
            'event': forms.TextInput(),
            'heading': forms.TextInput(),
            'location': forms.TextInput(),
            'source_url': forms.TextInput(),
        }
        exclude = ('celery_task_id', 'instance')
Exemplo n.º 11
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
Exemplo n.º 12
0
class ManageFolderForm(FileFormMixin, forms.ModelForm):
    """ Manage folder (in the modal). """

    image = UploadedFileField(required=False)

    parent = OnlyNameChoiceField(queryset=Folder.objects.all(),
                                 empty_label=_(u'(None)'),
                                 label=_(u'Parent folder'),
                                 required=False,
                                 widget=Select2Widget())

    subscriptions = OnlyNameMultipleChoiceField(
        label=_(u'Subscriptions'),
        queryset=Subscription.objects.none(),
        required=False,
        widget=Select2MultipleWidget(),
        help_text=_(u'These are the ones held directly by the folder; they '
                    u'are displayed above subfolders. There can be none, if '
                    u'you prefer dispatching your subscriptions in subfolders '
                    u'only.'))

    class Meta:
        model = Folder
        fields = (
            'name',
            'slug',
            'image_url',
            'parent',
            # 'is_shared', 'is_moderated', 'is_restricted',
            # 'anonymous_membership',
        )
        # widgets = {
        #     'name': forms.TextInput(),
        # }

    def __init__(self, *args, **kwargs):
        """ init(me). """

        self.folder_owner = kwargs.pop('owner')

        super(ManageFolderForm, self).__init__(*args, **kwargs)

        folders_tree = self.folder_owner.get_folders_tree(for_parent=True)

        if self.instance.id:
            try:
                folders_tree.exclude(id=self.instance.id)
            except ValueError:
                pass

            else:
                for f in self.instance.children_tree:
                    try:
                        folders_tree.exclude(id=f.id)

                    except ValueError:
                        # ValueError: list.remove(x): x not in list
                        # Happens when try to remove a level-N+ folder
                        # from a list limited to level N-1 folder. No
                        # need to continue, folders_tree return a
                        # depth-aware list.
                        break

            try:
                self.fields['subscriptions'].initial = \
                    self.folder_owner.subscriptions_by_folder[self.instance]

            except KeyError:
                # No subscriptions in this folder yet.
                pass

        self.fields['parent'].queryset = folders_tree
        self.fields['subscriptions'].queryset = \
            self.folder_owner.subscriptions.order_by('name')

    def clean_parent(self):
        """ Return root if no parent selected. """

        try:
            parent = self.cleaned_data['parent']

        except:
            return self.folder_owner.root_folder

        if parent is None:
            return self.folder_owner.root_folder

        return parent

    def is_valid(self):
        """ Check a lot of internal stuff to be useful to the user. """

        res = super(ManageFolderForm, self).is_valid()

        if not res:
            return False

        if self.instance.id is None:

            parent_folder = self.cleaned_data['parent']

            try:
                Folder.objects.get(user=self.folder_owner,
                                   name=self.cleaned_data['name'],
                                   parent=parent_folder)

            except Folder.DoesNotExist:
                return True

            else:
                if parent_folder == self.folder_owner.root_folder:
                    self._errors['already_exists'] = \
                        _(u'A top folder by that name already exists.')
                else:
                    self._errors['already_exists'] = \
                        _(u'A folder by that name already exists '
                          u'at the same place.')

                return False

        return True

    def save(self, commit=True):
        """ Save folder and synchronize_subscriptions_folders(). """

        if self.cleaned_data['image']:
            self.instance.image = self.cleaned_data['image']
        else:
            self.instance.image = None

        parent_folder = self.cleaned_data.get('parent')
        parent_changed = False

        # id == None means creation, else we are editing.
        if self.instance.id:

            # We need to get the previous values; Django doesn't cache
            # them and self.instance is already updated with new values.
            old_folder = Folder.objects.get(id=self.instance.id)

            if old_folder.parent != parent_folder:
                # The form.save() will set the new parent, but
                # will not unset instance from parent.children.
                # We need to take care of this.
                try:
                    old_folder.parent.children.remove(self.instance)

                except AttributeError:
                    # A top folder is becoming a sub-folder. It had no parent.
                    pass
                parent_changed = True

        else:
            # In "add folder" mode, parent has always changed, it's new!
            parent_changed = True

        folder = super(ManageFolderForm, self).save(commit=False)

        if self.instance.id is None:
            folder.user = self.folder_owner

        if commit:
            folder.save()

        if parent_changed:
            # In edit or create mode, we need to take care of the other
            # direction of the double-linked relation. This will imply
            # a superfluous write in case of an unchanged parent
            parent_folder.children.add(folder)

        self.synchronize_subscriptions_folders(folder)

        self.delete_temporary_files()

        return folder

    def synchronize_subscriptions_folders(self, folder):
        """ Move subscriptions from old folder to new, given user prefs.

        .. note:: `folder` is just self.instance passed
            through to avoid to look it up again.
        """

        try:
            initial_subscriptions = \
                self.folder_owner.subscriptions_by_folder[self.instance]

        except KeyError:
            initial_subscriptions = []

        updated_subscriptions = self.cleaned_data['subscriptions']

        for subscription in initial_subscriptions:
            if subscription not in updated_subscriptions:
                subscription.folders.remove(folder)

        if self.folder_owner.preferences.selector.subscriptions_in_multiple_folders:  # NOQA
            replace_folders = False

        else:
            replace_folders = True

        for subscription in updated_subscriptions:
            # This will update more things than needed, but in the case of
            # a changed preference, this will make the subscription appear
            # in one folder only again.
            # TODO: when the preference has a trigger on save() that do
            # this automatically, uncomment the following line to simply
            # move new subscriptions to this folder, and not touch others.
            #
            # if subscription not in initial_subscriptions:
            if replace_folders:
                subscription.folders.clear()

            subscription.folders.add(folder)