Exemplo n.º 1
0
class _UserProfileForm(forms.ModelForm):

    avatar = avatar_forms.AvatarField(required=False, disable_preview=True)
    website = forms.URLField(widget=forms.TextInput, required=False)
    language = forms.CharField(required=False)

    if settings.COSINNUS_USERPROFILE_ENABLE_NEWSLETTER_OPT_IN:
        newsletter_opt_in = forms.BooleanField(label='newsletter_opt_in',
                                               required=False)

    class Meta(object):
        model = get_user_profile_model()
        fields = model.get_optional_fieldnames()

    def __init__(self, *args, **kwargs):
        super(_UserProfileForm, self).__init__(*args, **kwargs)
        if settings.COSINNUS_USERPROFILE_ENABLE_NEWSLETTER_OPT_IN:
            self.initial['newsletter_opt_in'] = self.instance.settings.get(
                'newsletter_opt_in', False)

    def save(self, commit=True):
        """ Set the username equal to the userid """
        profile = super(_UserProfileForm, self).save(commit=True)

        # set the newsletter opt-in
        if settings.COSINNUS_USERPROFILE_ENABLE_NEWSLETTER_OPT_IN:
            profile.settings['newsletter_opt_in'] = self.cleaned_data.get(
                'newsletter_opt_in')
            profile.save(update_fields=['settings'])

        return profile
Exemplo n.º 2
0
class _UserProfileForm(forms.ModelForm):

    avatar = avatar_forms.AvatarField(required=False, disable_preview=True)
    website = forms.URLField(widget=forms.TextInput, required=False)
    language = forms.CharField(required=False)

    class Meta(object):
        model = get_user_profile_model()
        fields = model.get_optional_fieldnames()
Exemplo n.º 3
0
class AvatarForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['avatar']

    avatar = avatar_forms.AvatarField()

    error_messages = {
        "file_too_large": _("Image upload file is too large exceed 4mb."),
    }

    def clean_avatar(self):
        avatar = self.cleaned_data.get("avatar", None)
        file = avatar.get("file", None)
        if file and file.size > MAX_LENGTH:
            raise forms.ValidationError(self.error_messages["file_too_large"])
        return avatar

    """  
Exemplo n.º 4
0
class _UserProfileForm(UserProfileFormDynamicFieldsMixin, ManagedTagFormMixin,
                       forms.ModelForm):

    avatar = avatar_forms.AvatarField(required=False,
                                      disable_preview=True,
                                      validators=[validate_file_infection])
    website = forms.URLField(widget=forms.TextInput, required=False)
    language = forms.CharField(required=False)

    if settings.COSINNUS_USERPROFILE_ENABLE_NEWSLETTER_OPT_IN:
        newsletter_opt_in = forms.BooleanField(label='newsletter_opt_in',
                                               required=False)
    if settings.COSINNUS_MANAGED_TAGS_ENABLED and \
            (settings.COSINNUS_MANAGED_TAGS_USERS_MAY_ASSIGN_SELF or settings.COSINNUS_MANAGED_TAGS_ASSIGNABLE_IN_USER_ADMIN_FORM):
        managed_tag_field = forms.CharField(
            required=settings.
            COSINNUS_MANAGED_TAGS_USERPROFILE_FORMFIELD_REQUIRED)

    class Meta(object):
        model = get_user_profile_model()
        fields = model.get_optional_fieldnames()

    def __init__(self, *args, **kwargs):
        super(_UserProfileForm, self).__init__(*args, **kwargs)
        if settings.COSINNUS_USERPROFILE_ENABLE_NEWSLETTER_OPT_IN:
            self.initial['newsletter_opt_in'] = self.instance.settings.get(
                'newsletter_opt_in', False)

    def save(self, commit=True):
        """ Set the username equal to the userid """
        profile = super(_UserProfileForm, self).save(commit=True)

        # set the newsletter opt-in
        if settings.COSINNUS_USERPROFILE_ENABLE_NEWSLETTER_OPT_IN:
            profile.settings['newsletter_opt_in'] = self.cleaned_data.get(
                'newsletter_opt_in')
            profile.save(update_fields=['settings'])

        return profile
Exemplo n.º 5
0
class _CosinnusOrganizationForm(AsssignPortalMixin, AdditionalFormsMixin,
                                forms.ModelForm):

    extra_forms_setting = 'COSINNUS_ORGANIZATION_ADDITIONAL_FORMS'

    avatar = avatar_forms.AvatarField(required=getattr(
        settings, 'COSINNUS_GROUP_AVATAR_REQUIRED', False),
                                      disable_preview=True,
                                      validators=[validate_file_infection])

    class Meta(object):
        model = CosinnusOrganization
        fields = [
            'name', 'type', 'type_other', 'description', 'avatar', 'wallpaper',
            'website', 'email', 'phone_number'
        ]

    def __init__(self, instance, *args, **kwargs):
        if 'request' in kwargs:
            self.request = kwargs.pop('request')
        super(_CosinnusOrganizationForm, self).__init__(instance=instance,
                                                        *args,
                                                        **kwargs)
Exemplo n.º 6
0
class CosinnusBaseGroupForm(FacebookIntegrationGroupFormMixin,
                            MultiLanguageFieldValidationFormMixin,
                            forms.ModelForm):

    avatar = avatar_forms.AvatarField(required=False, disable_preview=True)
    website = forms.URLField(widget=forms.TextInput, required=False)
    # we want a textarea without character limit here so HTML can be pasted (will be cleaned)
    twitter_widget_id = forms.CharField(widget=forms.Textarea, required=False)

    related_groups = forms.ModelMultipleChoiceField(
        queryset=get_cosinnus_group_model().objects.filter(
            portal_id=CosinnusPortal.get_current().id))

    class Meta(object):
        fields = ['name', 'public', 'description', 'description_long', 'contact_info',
                        'avatar', 'wallpaper', 'website', 'video', 'twitter_username',
                         'twitter_widget_id', 'flickr_url', 'deactivated_apps', 'microsite_public_apps',
                         'call_to_action_active', 'call_to_action_title', 'call_to_action_description'] \
                        + getattr(settings, 'COSINNUS_GROUP_ADDITIONAL_FORM_FIELDS', []) \
                        + (['facebook_group_id', 'facebook_page_id',] if settings.COSINNUS_FACEBOOK_INTEGRATION_ENABLED else [])

    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)

    def clean(self):
        if not self.cleaned_data.get('name', None):
            name = self.get_cleaned_name_from_other_languages()
            if name:
                self.cleaned_data['name'] = name
                self.data['name'] = name
                if 'name' in self.errors:
                    del self.errors['name']
        return super(CosinnusBaseGroupForm, self).clean()

    def clean_video(self):
        data = self.cleaned_data['video']
        if data:
            parsed_video = self.instance.get_video_properties(video=data)
            if not parsed_video or 'error' in parsed_video:
                raise forms.ValidationError(
                    _('This doesn\'t seem to be a valid Youtube or Vimeo link!'
                      ))
        return data

    def clean_twitter_username(self):
        """ check username and enforce '@' """
        data = self.cleaned_data['twitter_username']
        if data:
            data = data.strip()
            if not TWITTER_USERNAME_VALID_RE.match(data):
                raise forms.ValidationError(
                    _('This doesn\'t seem to be a Twitter username!'))
            data = '@' + data.replace('@', '')
        return data

    def clean_twitter_widget_id(self):
        """ Accept Widget-id (example: 744907261810618721) or embed-code (HTML)
            always returns empty or a numeral like 744907261810618721 """
        data = self.cleaned_data['twitter_widget_id']
        if data:
            data = data.strip()
            if _is_number(data):
                return data
            match = TWITTER_WIDGET_EMBED_ID_RE.search(data)
            if match and _is_number(match.group(1)):
                return match.group(1)
            raise forms.ValidationError(
                _('This doesn\'t seem to be a valid widget ID or embed HTML code from Twitter!'
                  ))
        return data

    def clean_flickr_url(self):
        data = self.cleaned_data['flickr_url']
        if data:
            parsed_flickr = self.instance.get_flickr_properties(flickr=data)
            if not parsed_flickr or 'error' in parsed_flickr:
                raise forms.ValidationError(
                    _('This doesn\'t seem to be a valid Flickr Gallery link! It should be in the form of "https://www.flickr.com/photos/username/sets/1234567890"!'
                      ))
        return data

    def save(self, commit=True):
        """ Support for m2m-MultipleModelChoiceFields. Saves all selected relations.
            from http://stackoverflow.com/questions/2216974/django-modelform-for-many-to-many-fields """
        self.instance = super(CosinnusBaseGroupForm, self).save(commit=False)
        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m

        def save_m2m():
            old_save_m2m()
            self.instance.related_groups.clear()
            for related_group in self.cleaned_data['related_groups']:
                #self.instance.related_groups.add(related_group)
                # add() is disabled for a self-referential models, so we create an instance of the through-model
                RelatedGroups.objects.get_or_create(to_group=self.instance,
                                                    from_group=related_group)

        self.save_m2m = save_m2m
        if commit:
            self.instance.save()
            self.save_m2m()
        return self.instance
Exemplo n.º 7
0
class CosinnusBaseGroupForm(FacebookIntegrationGroupFormMixin, MultiLanguageFieldValidationFormMixin, 
                GroupFormDynamicFieldsMixin, ManagedTagFormMixin, FormAttachableMixin, 
                AdditionalFormsMixin, forms.ModelForm):
    
    avatar = avatar_forms.AvatarField(required=getattr(settings, 'COSINNUS_GROUP_AVATAR_REQUIRED', False), 
                  disable_preview=True, validators=[validate_file_infection])
    website = forms.URLField(widget=forms.TextInput, required=False)
    # we want a textarea without character limit here so HTML can be pasted (will be cleaned)
    twitter_widget_id = forms.CharField(widget=forms.Textarea, required=False)
    sdgs = forms.MultipleChoiceField(choices=SDG_CHOICES, required=False)
    
    related_groups = forms.ModelMultipleChoiceField(queryset=get_cosinnus_group_model().objects.none())
    
    if settings.COSINNUS_MANAGED_TAGS_ENABLED and settings.COSINNUS_MANAGED_TAGS_USERS_MAY_ASSIGN_GROUPS:
        managed_tag_field = forms.CharField(required=settings.COSINNUS_MANAGED_TAGS_GROUP_FORMFIELD_REQUIRED)
    
    class Meta(object):
        fields = ['name', 'public', 'description', 'description_long', 'contact_info', 'sdgs',
                        'avatar', 'wallpaper', 'website', 'video', 'twitter_username',
                         'twitter_widget_id', 'flickr_url', 'deactivated_apps', 'microsite_public_apps',
                         'call_to_action_active', 'call_to_action_title', 'call_to_action_description',
                         'membership_mode'] \
                        + getattr(settings, 'COSINNUS_GROUP_ADDITIONAL_FORM_FIELDS', []) \
                        + (['facebook_group_id', 'facebook_page_id',] if settings.COSINNUS_FACEBOOK_INTEGRATION_ENABLED else []) \
                        + (['embedded_dashboard_html',] if settings.COSINNUS_GROUP_DASHBOARD_EMBED_HTML_FIELD_ENABLED else []) \
                        + (['managed_tag_field',] if (settings.COSINNUS_MANAGED_TAGS_ENABLED \
                                                      and settings.COSINNUS_MANAGED_TAGS_USERS_MAY_ASSIGN_GROUPS) else [])

    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)
                
    def clean(self):
        if not self.cleaned_data.get('name', None):
            name = self.get_cleaned_name_from_other_languages()
            if name:
                self.cleaned_data['name'] = name
                self.data['name'] = name
                if 'name' in self.errors:
                    del self.errors['name'] 
        return super(CosinnusBaseGroupForm, self).clean()
        
    def clean_video(self):
        data = self.cleaned_data['video']
        if data:
            parsed_video = self.instance.get_video_properties(video=data)
            if not parsed_video or 'error' in parsed_video:
                raise forms.ValidationError(_('This doesn\'t seem to be a valid Youtube or Vimeo link!'))
        return data

    def clean_sdgs(self):
        if self.cleaned_data['sdgs'] and len(self.cleaned_data) > 0:
            return [int(sdg) for sdg in self.cleaned_data['sdgs']]
    
    def clean_twitter_username(self):
        """ check username and enforce '@' """
        data = self.cleaned_data['twitter_username']
        if data:
            data = data.strip()
            if not TWITTER_USERNAME_VALID_RE.match(data):
                raise forms.ValidationError(_('This doesn\'t seem to be a Twitter username!'))
            data = '@' + data.replace('@', '')
        return data
    
    def clean_twitter_widget_id(self):
        """ Accept Widget-id (example: 744907261810618721) or embed-code (HTML)
            always returns empty or a numeral like 744907261810618721 """
        data = self.cleaned_data['twitter_widget_id']
        if data:
            data = data.strip()
            if _is_number(data):
                return data
            match = TWITTER_WIDGET_EMBED_ID_RE.search(data)
            if match and _is_number(match.group(1)):
                return match.group(1)
            raise forms.ValidationError(_('This doesn\'t seem to be a valid widget ID or embed HTML code from Twitter!'))
        return data
    
    def clean_flickr_url(self):
        data = self.cleaned_data['flickr_url']
        if data:
            parsed_flickr = self.instance.get_flickr_properties(flickr=data)
            if not parsed_flickr or 'error' in parsed_flickr:
                raise forms.ValidationError(_('This doesn\'t seem to be a valid Flickr Gallery link! It should be in the form of "https://www.flickr.com/photos/username/sets/1234567890"!'))
        return data
    
    def save(self, commit=True):
        """ Support for m2m-MultipleModelChoiceFields. Saves all selected relations.
            from http://stackoverflow.com/questions/2216974/django-modelform-for-many-to-many-fields """
        self.instance = super(CosinnusBaseGroupForm, self).save(commit=False)
        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m
        def save_m2m():
            old_save_m2m()
            
            new_group_slugs = [new_group.slug for new_group in self.cleaned_data['related_groups']]
            old_related_group_slugs = self.instance.related_groups.all().values_list('slug', flat=True)
            # remove no longer wanted related_groups
            for old_slug in old_related_group_slugs:
                if old_slug not in new_group_slugs:
                    old_group_rel = get_object_or_None(RelatedGroups, to_group=self.instance, from_group__slug=old_slug)
                    old_group_rel.delete()
            # add new related_groups
            user_group_ids = get_cosinnus_group_model().objects.get_for_user_pks(self.request.user)
            user_superuser = check_user_superuser(self.request.user)
            
            
            conference_notification_pairs = []
            for related_group in self.cleaned_data['related_groups']:
                # non-superuser users can only tag groups they are in
                if not user_superuser and related_group.id not in user_group_ids:
                    continue
                # only create group rel if it didn't exist
                existing_group_rel = get_object_or_None(RelatedGroups, to_group=self.instance, from_group=related_group)
                if not existing_group_rel:
                    # create a new related group link
                    RelatedGroups.objects.create(to_group=self.instance, from_group=related_group) 
                    # if the current group is a conference, and the related group is a society or project,
                    # the conference will be reflected into the group, so we send a notification
                    non_conference_group_types = [get_cosinnus_group_model().TYPE_PROJECT, get_cosinnus_group_model().TYPE_SOCIETY]
                    if self.instance.group_is_conference and related_group.type in non_conference_group_types:
                        audience_except_creator = [member for member in related_group.actual_members if member.id != self.request.user.id]
                        # set the target group for the notification onto the group instance
                        setattr(self.instance, 'notification_target_group', related_group)
                        conference_notification_pairs.append((self.instance, audience_except_creator))
            
            # send notifications in a session to avoid duplicate messages to any user
            session_id = uuid1().int     
            for i, pair in enumerate(conference_notification_pairs):
                cosinnus_notifications.conference_created_in_group.send(
                    sender=self,
                    user=self.request.user,
                    obj=pair[0],
                    audience=pair[1],
                    session_id=session_id,
                    end_session=bool(i == len(conference_notification_pairs)-1)
                )
        
        self.save_m2m = save_m2m
        if commit:
            self.instance.save()
            # we skip the call to `save_m2m` here, because the django-multiform `MultiModelForm` already calls it!
            # self.save_m2m()
            
            # since we didn't call super().save with commit=True, call this for certain forms to catch up
            if hasattr(self, 'post_uncommitted_save'):
                self.post_uncommitted_save(self.instance)
        return self.instance
Exemplo n.º 8
0
class UploadAndCropImageForm(forms.ModelForm):
    image = avatar_forms.AvatarField()