Example #1
0
class MultiFileForm(BetterForm):
    files = MultiFileField(min_num=1)
    group = forms.ChoiceField(required=True, choices=[])
    tags = forms.CharField(required=False)

    file_cat = forms.ModelChoiceField(
        label=_("Category"),
        queryset=FilesCategory.objects.filter(parent=None),
        empty_label="-----------",
        required=False)
    file_sub_cat = forms.ModelChoiceField(
        label=_("Sub-Category"),
        queryset=FilesCategory.objects.none(),
        empty_label=_("Please choose a category first"),
        required=False)

    allow_anonymous_view = forms.BooleanField(label=_("Public can View"),
                                              initial=True,
                                              required=False)

    group_perms = GroupPermissionField()
    user_perms = UserPermissionField()
    member_perms = MemberPermissionField()

    class Meta:
        fieldsets = (
            (_('File Information'), {
                'fields': (
                    'files',
                    'tags',
                    'group',
                )
            }),
            (_('Category'), {
                'fields': ('file_cat', 'file_sub_cat')
            }),
            (_('Permissions'), {
                'fields': ('allow_anonymous_view', )
            }),
            (_('Advanced Permissions'), {
                'classes': ('collapse', ),
                'fields': (
                    'user_perms',
                    'member_perms',
                    'group_perms',
                )
            }),
        )

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

        super(MultiFileForm, self).__init__(*args, **kwargs)
        default_groups = Group.objects.filter(status=True,
                                              status_detail="active")

        if args:
            post_data = args[0]
        else:
            post_data = None

        if self.user and not self.user.profile.is_superuser:
            filters = get_query_filters(self.user, 'user_groups.view_group',
                                        **{'perms_field': False})
            groups = default_groups.filter(filters).distinct()
            groups_list = list(groups.values_list('pk', 'name'))

            users_groups = self.user.profile.get_groups()
            for g in users_groups:
                if [g.id, g.name] not in groups_list:
                    groups_list.append([g.id, g.name])
        else:
            groups_list = default_groups.values_list('pk', 'name')

        self.fields['group'].choices = groups_list

        # set up the sub category choices
        if post_data:
            file_cat = post_data.get('file_cat', '0')
            if file_cat and file_cat != '0' and file_cat != u'':
                [file_cat] = FilesCategory.objects.filter(
                    pk=int(file_cat))[:1] or [None]
                if file_cat:
                    self.fields[
                        'file_sub_cat'].queryset = FilesCategory.objects.filter(
                            parent=file_cat)

    def clean_files(self):
        files = self.cleaned_data.get('files')
        max_upload_size = get_max_file_upload_size(file_module=True)
        for data in files:
            if data.size > max_upload_size:
                raise forms.ValidationError(
                    _('Please keep filesize under %(max_upload_size)s. Current filesize %(data_size)s'
                      ) % {
                          'max_upload_size': filesizeformat(max_upload_size),
                          'data_size': filesizeformat(data.size)
                      })

        return files

    def clean_user_perms(self):
        user_perm_bits = []
        value = self.cleaned_data['user_perms']
        if value:
            if 'allow_user_view' in value:
                user_perm_bits.append(True)
            else:
                user_perm_bits.append(False)

            if 'allow_user_edit' in value:
                user_perm_bits.append(True)
            else:
                user_perm_bits.append(False)
            value = tuple(user_perm_bits)
        else:
            value = (
                False,
                False,
            )
        return value

    def clean_member_perms(self):
        member_perm_bits = []
        value = self.cleaned_data['member_perms']
        if value:
            if 'allow_member_view' in value:
                member_perm_bits.append(True)
            else:
                member_perm_bits.append(False)

            if 'allow_member_edit' in value:
                member_perm_bits.append(True)
            else:
                member_perm_bits.append(False)
            value = tuple(member_perm_bits)
        else:
            value = (
                False,
                False,
            )
        return value

    def clean_group_perms(self):
        value = self.cleaned_data['group_perms']
        groups_and_perms = []
        if value:
            for item in value:
                perm, group_pk = item.split('_')
                groups_and_perms.append((
                    group_pk,
                    perm,
                ))
            value = tuple(groups_and_perms)
        return value

    def clean_group(self):
        group_id = self.cleaned_data['group']

        try:
            group = Group.objects.get(pk=group_id)
            return group
        except Group.DoesNotExist:
            raise forms.ValidationError(_('Invalid group selected.'))

    def save(self, *args, **kwargs):
        data = self.cleaned_data
        counter = 0

        files = data.get('files')
        tags = data.get('tags')
        group = data.get('group')
        file_cat = data.get('file_cat', None)
        file_sub_cat = data.get('file_sub_cat', None)
        is_public = data.get('allow_anonymous_view', False)

        for new_file in files:
            file = File(file=new_file,
                        tags=tags,
                        group=group,
                        allow_anonymous_view=is_public,
                        file_cat=file_cat,
                        file_sub_cat=file_sub_cat)

            file.save()

            # update all permissions and save the model
            file = update_perms_and_save(self.request, self, file)

            #setup categories
            category = Category.objects.get_for_object(file, 'category')
            sub_category = Category.objects.get_for_object(
                file, 'sub_category')

            ## update the category of the file
            category_removed = False
            category = file.file_cat.name if file.file_cat else u''

            if category:
                Category.objects.update(file, category, 'category')
            else:  # remove
                category_removed = True
                Category.objects.remove(file, 'category')
                Category.objects.remove(file, 'sub_category')

            if not category_removed:
                # update the sub category of the file
                sub_category = file.file_sub_cat.name if file.file_sub_cat else u''
                if sub_category:
                    Category.objects.update(file, sub_category, 'sub_category')
                else:  # remove
                    Category.objects.remove(file, 'sub_category')

            #Save relationships
            file.save()
            counter += 1

        return counter
Example #2
0
class TendenciBaseForm(FormControlWidgetMixin, BetterModelForm):
    """
    Base form that adds user permission fields
    """
    group_perms = GroupPermissionField()
    user_perms = UserPermissionField()
    member_perms = MemberPermissionField()
    # override due to the changes for BooleanField to NullBooleanField
    allow_anonymous_view = forms.BooleanField(label=_('Public can view'), required=False, initial=True)

    def clean_user_perms(self):
        user_perm_bits = []
        value = self.cleaned_data['user_perms']
        if value:
            if 'allow_user_view' in value:
                user_perm_bits.append(True)
            else:
                user_perm_bits.append(False)

            if 'allow_user_edit' in value:
                user_perm_bits.append(True)
            else:
                user_perm_bits.append(False)
            value = tuple(user_perm_bits)
        else:
            value = (False, False,)
        return value

    def clean_member_perms(self):
        member_perm_bits = []
        value = self.cleaned_data['member_perms']
        if value:
            if 'allow_member_view' in value:
                member_perm_bits.append(True)
            else:
                member_perm_bits.append(False)

            if 'allow_member_edit' in value:
                member_perm_bits.append(True)
            else:
                member_perm_bits.append(False)
            value = tuple(member_perm_bits)
        else:
            value = (False, False,)
        return value

    def clean_group_perms(self):
        value = self.cleaned_data['group_perms']
        groups_and_perms = []
        if value:
            for item in value:
                perm, group_pk = item.split('_')
                groups_and_perms.append((group_pk, perm,))
            value = tuple(groups_and_perms)
        return value

    def clean_allow_anonymous_view(self):
        data = self.cleaned_data.get('allow_anonymous_view', False)
        if data:
            return True
        else:
            return False

    def __init__(self, *args, **kwargs):
        from tendenci.apps.perms.fields import user_perm_bits, member_perm_bits
        if 'user' in kwargs:
            self.user = kwargs.pop('user', None)
        else:
            if not hasattr(self, 'user'):
                self.user = None

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

        # needs to update the choices on every pull
        # in case groups get added
        if 'group_perms' in self.fields:
            self.fields['group_perms'].choices = group_choices()

        instance = kwargs.get('instance', None)
        if instance:
            if 'group_perms' in self.fields:
                self.fields['group_perms'].initial = groups_with_perms(instance)
            if 'user_perms' in self.fields:
                self.fields['user_perms'].initial = user_perm_bits(instance)
            if 'member_perms' in self.fields:
                self.fields['member_perms'].initial = member_perm_bits(instance)