class Meta: model = Organisation fields = ('name_native', 'homepage', 'source_urls', 'google_plus_page', 'facebook_page', 'twitter_page', 'founded', 'coordinates_type', 'is_private', 'is_live', 'location', 'neighbour_distance', 'transregional_distance', 'timezone') years_to_display = range(datetime.datetime.now().year - 100, datetime.datetime.now().year + 1) widgets = { 'homepage': bootstrap.URLInput(attrs={'size': 50}), 'source_urls': bootstrap.Textarea(attrs={'rows': '3'}), 'google_plus_page': bootstrap.URLInput(attrs={'size': 50}), 'facebook_page': bootstrap.URLInput(attrs={'size': 50}), 'twitter_page': bootstrap.URLInput(attrs={'size': 50}), 'association': bootstrap.Select(), 'name': bootstrap.TextInput(attrs={'size': 50}), 'name_native': bootstrap.TextInput(attrs={'size': 50}), 'founded': bootstrap.SelectDateWidget(years=years_to_display), 'coordinates_type': bootstrap.Select(), 'center_type': bootstrap.Select(), 'is_private': bootstrap.CheckboxInput(), 'is_active': bootstrap.CheckboxInput(), 'is_live': bootstrap.CheckboxInput(), 'timezone': bootstrap.Select2(), 'location': bootstrap.OSMWidget(), 'neighbour_distance': bootstrap.TextInput(attrs={ 'type': 'number', 'step': '0.001' }), 'transregional_distance': bootstrap.TextInput(attrs={ 'type': 'number', 'step': '0.001' }), }
class Meta: model = OrganisationPhoneNumber fields = ('phone_type', 'phone') widgets = { 'phone_type': bootstrap.Select(), 'phone': bootstrap.TextInput(attrs={'size': 50}), }
class OrganisationPictureForm(BaseStackedInlineForm): order = forms.IntegerField( label=_("Order"), required=False, widget=bootstrap.Select(choices=BLANK_CHOICE_DASH + list(zip(range(3), range(3))))) class Meta: model = OrganisationPicture fields = ('picture', 'title', 'description', 'order') widgets = { 'title': bootstrap.TextInput(attrs={'size': 50}), 'description': bootstrap.Textarea(), 'picture': bootstrap.ImageWidget(), } def clean_order(self): order = self.cleaned_data["order"] if order is None: order = 0 return order def clean_picture(self): picture = self.cleaned_data["picture"] return clean_picture(picture, OrganisationPicture.MAX_PICTURE_SIZE)
class Meta: model = UserPhoneNumber fields = ('phone_type', 'phone', 'primary') widgets = { 'phone_type': bootstrap.Select(), 'phone': bootstrap.TextInput(attrs={'size': 50}), 'primary': bootstrap.CheckboxInput() }
class Meta: model = OrganisationCountry fields = ('association', 'homepage', 'country_groups', 'country', 'is_active') widgets = { 'homepage': bootstrap.TextInput(attrs={'size': 50}), 'association': bootstrap.Select(), 'country': bootstrap.Select2(), }
class ApplicationRoleForm(BaseTabularInlineForm): role = forms.ModelChoiceField(queryset=Role.objects.filter(is_active=True), widget=bootstrap.Select()) class Meta: model = ApplicationRole fields = ( 'role', 'is_inheritable_by_org_admin', 'is_inheritable_by_global_admin', 'is_organisation_related', ) widgets = { 'is_inheritable_by_org_admin': bootstrap.CheckboxInput(), 'is_inheritable_by_global_admin': bootstrap.CheckboxInput(), 'is_organisation_related': bootstrap.CheckboxInput(), }
class Meta: model = OrganisationAddress fields = ('address_type', 'addressee', 'careof', 'street_address', 'city', 'city_native', 'postal_code', 'country', 'region') widgets = { 'address_type': bootstrap.Select(attrs={'class': 'address_type'}), 'addressee': bootstrap.TextInput(attrs={'size': 50}), 'careof': bootstrap.TextInput(attrs={'size': 50}), 'street_address': bootstrap.Textarea(attrs={ 'cols': 50, 'rows': 2 }), 'city': bootstrap.TextInput(attrs={'size': 50}), 'city_native': bootstrap.TextInput(attrs={'size': 50}), 'postal_code': bootstrap.TextInput(attrs={'size': 50}), 'region': bootstrap.TextInput(attrs={'size': 50}), }
class Meta: model = UserAddress fields = ('primary', 'address_type', 'addressee', 'street_address', 'city', 'city_native', 'postal_code', 'country', 'region') widgets = { 'primary': bootstrap.CheckboxInput(), 'address_type': bootstrap.Select(), 'addressee': bootstrap.TextInput(attrs={'size': 50}), 'street_address': bootstrap.Textarea(attrs={ 'cols': 50, 'rows': 2 }), 'city': bootstrap.TextInput(attrs={'size': 50}), 'city_native': bootstrap.TextInput(attrs={'size': 50}), 'postal_code': bootstrap.TextInput(attrs={'size': 50}), 'country': bootstrap.Select2(), 'region': bootstrap.TextInput(attrs={'size': 50}), }
class ClientForm(BaseForm): can_access_all_users = forms.BooleanField(label=_('Can access all users'), required=False, widget=bootstrap.CheckboxInput()) type = forms.ChoiceField( label=_('Type'), help_text=mark_safe_lazy( _("Confidential client (can store a secret) or public client for <a href='https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowSteps'>authorisation code flow</a> " "or service account client with <a href='https://datatracker.ietf.org/doc/html/rfc6749#section-4.4'>client credentials grant</a>." )), required=True, choices=ALLOWED_CLIENT_TYPES, widget=bootstrap.Select()) uuid = forms.UUIDField( label=_('Client ID'), required=True, initial=uuid.uuid4, widget=bootstrap.TextInput(attrs={'readonly': True})) scopes = forms.MultipleChoiceField(label=_('Scopes'), required=False, initial=['openid'], choices=ALLOWED_SCOPES, widget=bootstrap.Select2Multiple()) class Meta: model = Client fields = ('application', 'uuid', 'client_secret', 'name', 'type', 'redirect_uris', 'post_logout_redirect_uris', 'notes', 'is_active', 'scopes') widgets = { 'application': bootstrap.HiddenInput(), 'name': bootstrap.TextInput(attrs={'size': 50}), 'client_secret': bootstrap.TextInput(attrs={'readonly': True}), 'notes': bootstrap.Textarea(attrs={'rows': '3'}), 'redirect_uris': bootstrap.Textarea(attrs={'rows': '3'}), 'post_logout_redirect_uris': bootstrap.Textarea(attrs={'rows': '3'}), 'is_active': bootstrap.CheckboxInput(), } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') # remove custom user keyword # initialize scopes if kwargs.get('instance'): instance = kwargs['instance'] if instance.scopes: kwargs['initial']['scopes'] = instance.scopes.split() kwargs['initial'][ 'can_access_all_users'] = instance.has_access_to_all_users super().__init__(*args, **kwargs) def clean_scopes(self): scopes = self.cleaned_data['scopes'] return ' '.join(scopes) def clean(self): cleaned_data = super().clean() client_type = cleaned_data.get("type") client_secret = cleaned_data.get("client_secret") redirect_uris = cleaned_data.get("redirect_uris") if client_type in ['web', 'service']: if not client_secret: self.add_error( 'client_secret', ValidationError( "A client secret is required for this client type.")) if client_type == "native": cleaned_data['client_secret'] = '' if client_type in ['web', 'native']: if not redirect_uris: self.add_error( 'redirect_uris', ValidationError( "A redirect uri is required for this client type.")) else: cleaned_data['redirect_uris'] = '' cleaned_data['post_logout_redirect_uris'] = '' return self.cleaned_data def save(self, commit=True): instance = super().save(commit) # service clients need a user associated with if self.instance.type == 'service': instance.ensure_service_user_exists() can_access_all_users = self.cleaned_data['can_access_all_users'] if can_access_all_users is not None: instance.set_access_to_all_users(can_access_all_users, self.user) else: self.instance.remove_service_user() return instance
class UserProfileForm(mixins.UserRolesMixin, mixins.UserNoteMixin, forms.Form): """ Form for SSO Staff """ error_messages = { 'duplicate_username': _("A user with that username already exists."), 'duplicate_email': _("A user with that email address already exists."), } username = forms.CharField(label=_("Username"), max_length=40, validators=[UnicodeUsernameValidator()], widget=bootstrap.TextInput()) valid_until = bootstrap.ReadOnlyField(label=_("Valid until")) first_name = forms.CharField(label=_('First name'), max_length=30, widget=bootstrap.TextInput()) last_name = forms.CharField(label=_('Last name'), max_length=30, widget=bootstrap.TextInput()) gender = forms.ChoiceField(label=_('Gender'), required=False, choices=(BLANK_CHOICE_DASH + User.GENDER_CHOICES), widget=bootstrap.Select()) dob = forms.DateField(label=_('Date of birth'), required=False, widget=bootstrap.SelectDateWidget( years=range(datetime.datetime.now().year - 100, datetime.datetime.now().year + 1))) status = bootstrap.ReadOnlyField(label=_('Status')) organisations = forms.ModelChoiceField( queryset=None, required=settings.SSO_ORGANISATION_REQUIRED, label=_("Organisation"), widget=bootstrap.Select2()) application_roles = forms.MultipleChoiceField( required=False, widget=bootstrap.FilteredSelectMultiple(_("Application roles")), label=_("Additional application roles"), help_text=mixins.UserRolesMixin.application_roles_help) notes = forms.CharField(label=_("Notes"), required=False, max_length=1024, widget=bootstrap.Textarea(attrs={ 'cols': 40, 'rows': 10 })) role_profiles = forms.MultipleChoiceField( required=False, widget=bootstrap.CheckboxSelectMultiple(), label=_("Role profiles"), help_text=mixins.UserRolesMixin.role_profiles_help) created_by_user = forms.CharField( label=_("Created by"), required=False, widget=bootstrap.TextInput(attrs={'disabled': ''})) last_modified_by_user = forms.CharField( label=_("Last modified by"), required=False, widget=bootstrap.TextInput(attrs={'disabled': ''})) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.user = kwargs.pop('instance') user_data = model_to_dict(self.user) user_data['status'] = _('active') if self.user.is_active else _( 'blocked') user_data['role_profiles'] = [ role_profile.id for role_profile in self.user.role_profiles.all() ] user_data['application_roles'] = [ application_role.id for application_role in self.user.application_roles.all() ] if self.user.organisations.count() == 1: user_data['organisations'] = self.user.organisations.first() initial = kwargs.get('initial', {}) initial.update(user_data) initial[ 'created_by_user'] = self.user.created_by_user if self.user.created_by_user else '' initial[ 'last_modified_by_user'] = self.user.last_modified_by_user if self.user.last_modified_by_user else '' kwargs['initial'] = initial super().__init__(*args, **kwargs) self.fields['application_roles'].choices = [] app_roles_by_profile = ApplicationRole.objects.filter( roleprofile__user__id=self.user.pk).only("id") for application_role in self.request.user.get_administrable_application_roles( ): app_role_text = str(application_role) if application_role in app_roles_by_profile: app_role_text += " *" self.fields['application_roles'].choices.append( (application_role.id, app_role_text)) self.fields['role_profiles'].choices = [ (role_profile.id, role_profile) for role_profile in self.request.user.get_administrable_role_profiles() ] if self.user.organisations.count() > 1: self.fields['organisations'] = forms.ModelMultipleChoiceField( queryset=None, required=settings.SSO_ORGANISATION_REQUIRED, widget=bootstrap.SelectMultipleWithCurrently( currently=', '.join( [str(x) for x in self.user.organisations.all()])), label=_("Organisation")) self.fields['organisations'].queryset = self.request.user.get_administrable_user_organisations(). \ filter(is_active=True, association__is_selectable=True) def clean_username(self): username = self.cleaned_data["username"] try: get_user_model().objects.exclude(pk=self.user.pk).get( username=username) except ObjectDoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) def save(self, extend_validity=False, activate=None, remove_org=False, make_member=False): cd = self.cleaned_data current_user = self.request.user if remove_org: new_orgs = set() removed_orgs = list(self.user.organisations.all()) else: removed_orgs = None new_orgs = None self.update_user_m2m_fields('organisations', current_user, new_value_set=new_orgs) self.update_user_m2m_fields('application_roles', current_user) self.update_user_m2m_fields('role_profiles', current_user) if remove_org: self.user.remove_organisation_related_permissions() self.user.username = cd['username'] self.user.first_name = cd['first_name'] self.user.last_name = cd['last_name'] self.user.gender = cd['gender'] self.user.dob = cd['dob'] if activate is not None: self.user.is_active = activate self.create_note_if_required(current_user, cd, activate, extend_validity, removed_orgs) if make_member: dwbn_member_profile = RoleProfile.objects.get_by_natural_key( uuid=settings.SSO_DEFAULT_MEMBER_PROFILE_UUID) self.user.role_profiles.add(dwbn_member_profile) if extend_validity or make_member: # enable brand specific modification valid_until = now() + datetime.timedelta( days=settings.SSO_VALIDATION_PERIOD_DAYS) extend_user_validity.send_robust(sender=self.__class__, user=self.user, valid_until=valid_until, admin=self.request.user) self.user.valid_until = valid_until self.user.save() return self.user
class UserSelfProfileForm(forms.Form): """ Form for the user himself to change editable values """ username = bootstrap.ReadOnlyField(label=_("Username")) valid_until = bootstrap.ReadOnlyField(label=_("Valid until")) first_name = forms.CharField(label=_('First name'), max_length=30, widget=bootstrap.TextInput()) last_name = forms.CharField(label=_('Last name'), max_length=30, widget=bootstrap.TextInput()) picture = Base64ImageField( label=_('Your picture'), required=False, help_text=_('Please use a photo of your face.'), widget=bootstrap.ClearableBase64ImageWidget( attrs={ 'max_file_size': settings.SSO_USER_MAX_PICTURE_SIZE, 'width': settings.SSO_USER_PICTURE_WIDTH, 'height': settings.SSO_USER_PICTURE_HEIGHT, })) gender = forms.ChoiceField(label=_('Gender'), required=False, choices=(BLANK_CHOICE_DASH + User.GENDER_CHOICES), widget=bootstrap.Select()) dob = forms.DateField(label=_('Date of birth'), required=False, widget=bootstrap.SelectDateWidget( years=range(datetime.datetime.now().year - 100, datetime.datetime.now().year + 1))) homepage = forms.URLField(label=_('Homepage'), required=False, max_length=512, widget=bootstrap.TextInput()) language = forms.ChoiceField( label=_("Language"), required=False, choices=(BLANK_CHOICE_DASH + sorted(list(settings.LANGUAGES), key=lambda x: x[1])), widget=bootstrap.Select2()) timezone = forms.ChoiceField( label=_("Timezone"), required=False, choices=BLANK_CHOICE_DASH + list(zip(pytz.common_timezones, pytz.common_timezones)), widget=bootstrap.Select2()) error_messages = { 'duplicate_username': _("A user with that username already exists."), } def __init__(self, *args, **kwargs): self.user = kwargs.pop('instance') object_data = model_to_dict(self.user) initial = kwargs.get('initial', {}) object_data.update(initial) kwargs['initial'] = object_data super().__init__(*args, **kwargs) organisation_field = bootstrap.ReadOnlyField( initial=', '.join([str(x) for x in self.user.organisations.all()]), label=_("Organisation"), help_text= _('Please use the contact form for a request to change this value.' )) self.fields['organisation'] = organisation_field def clean_organisation(self): if self.user.organisations.exists(): # if already assigned to an organisation return None, (readonly use case) return None else: return self.cleaned_data['organisation'] def save(self): cd = self.cleaned_data if (not self.initial['first_name'] and not self.initial['last_name']) and cd.get('first_name') \ and cd.get('last_name'): # should be a streaming user, which has no initial first_name and last_name # we create the new username because the streaming user has his email as username self.user.username = default_username_generator( capfirst(cd.get('first_name')), capfirst(cd.get('last_name'))) self.user.first_name = cd['first_name'] self.user.last_name = cd['last_name'] if 'picture' in self.changed_data: self.user.picture.delete(save=False) self.user.picture = cd['picture'] if cd['picture'] else None self.user.dob = cd.get('dob', None) self.user.gender = cd['gender'] self.user.homepage = cd['homepage'] self.user.language = cd['language'] self.user.timezone = cd['timezone'] self.user.save() if 'organisation' in cd and cd['organisation']: # user selected an organisation, this can only happen if the user before had # no organisation (see clean_organisation). self.user.set_organisations([cd["organisation"]])
class UserAddForm(mixins.UserRolesMixin, mixins.UserNoteMixin, forms.ModelForm): """ form for SSO User Admins for adding users in the frontend """ email = forms.EmailField(label=_('Email'), required=True, widget=bootstrap.EmailInput()) first_name = forms.CharField( label=_('First name'), required=True, widget=bootstrap.TextInput( attrs={'placeholder': capfirst(_('first name'))})) last_name = forms.CharField( label=_('Last name'), required=True, widget=bootstrap.TextInput( attrs={'placeholder': capfirst(_('last name'))})) gender = forms.ChoiceField(label=_('Gender'), required=True, choices=(BLANK_CHOICE_DASH + User.GENDER_CHOICES), widget=bootstrap.Select()) dob = forms.DateField(label=_('Date of birth'), required=False, widget=bootstrap.SelectDateWidget( years=range(datetime.datetime.now().year - 100, datetime.datetime.now().year + 1))) notes = forms.CharField(label=_("Notes"), required=False, max_length=1024, widget=bootstrap.Textarea(attrs={ 'cols': 40, 'rows': 10 })) organisations = forms.ModelChoiceField( queryset=None, required=settings.SSO_ORGANISATION_REQUIRED, label=_("Organisation"), widget=bootstrap.Select2()) application_roles = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=bootstrap.FilteredSelectMultiple(_("Application roles")), label=_("Additional application roles"), help_text=mixins.UserRolesMixin.application_roles_help) role_profiles = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=bootstrap.CheckboxSelectMultiple(), label=_("Role profiles"), help_text=mixins.UserRolesMixin.role_profiles_help) error_messages = { 'duplicate_email': _("A user with that email address already exists."), } class Meta: model = User fields = ("first_name", "last_name", 'gender', 'dob', 'notes', 'application_roles', 'role_profiles') def __init__(self, request, *args, **kwargs): self.request = request user = request.user super().__init__(*args, **kwargs) self.fields[ 'application_roles'].queryset = user.get_administrable_application_roles( ) self.fields[ 'role_profiles'].queryset = user.get_administrable_role_profiles() self.fields['organisations'].queryset = user.get_administrable_user_organisations(). \ filter(is_active=True, association__is_selectable=True) if not user.has_perm("accounts.access_all_users"): self.fields['organisations'].required = True def clean_email(self): # Check if email is unique, email = self.cleaned_data["email"] try: User.objects.get_by_email(email) raise forms.ValidationError(self.error_messages['duplicate_email']) except ObjectDoesNotExist: pass return email def save(self, commit=True): user = super().save(commit=False) user.set_password(get_random_string(40)) user.username = default_username_generator( capfirst(self.cleaned_data.get('first_name')), capfirst(self.cleaned_data.get('last_name'))) organisation = self.cleaned_data["organisations"] if is_validation_period_active(organisation): user.valid_until = now() + datetime.timedelta( days=settings.SSO_VALIDATION_PERIOD_DAYS) user.save() # use mixin to send notification self.user = user current_user = self.request.user self.update_user_m2m_fields('organisations', current_user) self.update_user_m2m_fields('application_roles', current_user) self.update_user_m2m_fields('role_profiles', current_user) self.create_note_if_required(current_user, self.cleaned_data) user.create_primary_email(email=self.cleaned_data["email"]) return user
class RegistrationProfileForm(mixins.UserRolesMixin, forms.Form): """ Form for organisation and region admins """ error_messages = { 'duplicate_username': _("A user with that username already exists."), 'duplicate_email': _("A user with that email address already exists."), } username = forms.CharField(label=_("Username"), max_length=30, widget=bootstrap.TextInput()) notes = forms.CharField(label=_("Notes"), required=False, max_length=1024, widget=bootstrap.Textarea(attrs={ 'cols': 40, 'rows': 10 })) first_name = forms.CharField(label=_('First name'), max_length=30, widget=bootstrap.TextInput()) last_name = forms.CharField(label=_('Last name'), max_length=30, widget=bootstrap.TextInput()) email = forms.EmailField( label=_('Email address'), required=False, widget=bootstrap.TextInput(attrs={'disabled': ''})) date_registered = bootstrap.ReadOnlyField(label=_("Date registered")) country = bootstrap.ReadOnlyField(label=_("Country")) city = bootstrap.ReadOnlyField(label=_("City")) language = bootstrap.ReadOnlyField(label=_("Language")) timezone = bootstrap.ReadOnlyField(label=_("Timezone")) gender = forms.ChoiceField(label=_('Gender'), required=False, choices=(BLANK_CHOICE_DASH + User.GENDER_CHOICES), widget=bootstrap.Select()) dob = forms.CharField(label=_("Date of birth"), required=False, widget=bootstrap.TextInput(attrs={'disabled': ''})) about_me = forms.CharField(label=_('About me'), required=False, widget=bootstrap.Textarea(attrs={ 'cols': 40, 'rows': 5, 'readonly': 'readonly' })) known_person1_first_name = forms.CharField(label=_("First name"), max_length=100, required=False, widget=bootstrap.TextInput()) known_person1_last_name = forms.CharField(label=_("Last name"), max_length=100, required=False, widget=bootstrap.TextInput()) known_person2_first_name = forms.CharField(label=_("First name"), max_length=100, required=False, widget=bootstrap.TextInput()) known_person2_last_name = forms.CharField(label=_("Last name"), max_length=100, required=False, widget=bootstrap.TextInput()) last_modified_by_user = forms.CharField( label=_("Last modified by"), required=False, widget=bootstrap.TextInput(attrs={'disabled': ''})) organisations = forms.ModelChoiceField( queryset=None, label=_("Organisation"), widget=bootstrap.Select2(), required=settings.SSO_ORGANISATION_REQUIRED) application_roles = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=bootstrap.FilteredSelectMultiple(_("Application roles")), label=_("Additional application roles"), help_text=mixins.UserRolesMixin.application_roles_help) check_back = forms.BooleanField( label=_("Check back"), help_text=_('Designates if there are open questions to check.'), required=False, disabled=True) is_access_denied = forms.BooleanField( label=_("Access denied"), help_text=_('Designates if access is denied to the user.'), required=False, disabled=True) is_stored_permanently = forms.BooleanField( label=_("Store permanantly"), help_text=_( 'Keep stored in database to prevent re-registration of denied user.' ), required=False) role_profiles = forms.MultipleChoiceField( required=False, widget=bootstrap.CheckboxSelectMultiple(), label=_("Role profiles"), help_text=mixins.UserRolesMixin.role_profiles_help) def clean_username(self): username = self.cleaned_data["username"] try: get_user_model().objects.exclude(pk=self.user.pk).get( username=username) except ObjectDoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.registrationprofile = kwargs.pop('instance') self.user = self.registrationprofile.user registrationprofile_data = model_to_dict(self.registrationprofile) user_data = model_to_dict(self.user) if self.user.language: user_data['language'] = self.user.get_language_display() try: # after registration, the user should have exactly 1 center user_data['organisations'] = self.user.organisations.first() except ObjectDoesNotExist: # center is optional # logger.error("User without center?", exc_info=1) pass # initialize form correctly user_data['role_profiles'] = [ str(role_profile.id) for role_profile in self.user.role_profiles.all() ] address_data = {} if self.user.useraddress_set.exists(): useraddress = self.user.useraddress_set.first() address_data = model_to_dict(useraddress) address_data['country'] = useraddress.country initial = kwargs.get('initial', {}) initial.update(registrationprofile_data) initial.update(user_data) initial.update(address_data) initial['email'] = self.user.primary_email() last_modified_by_user = self.registrationprofile.last_modified_by_user initial[ 'last_modified_by_user'] = last_modified_by_user if last_modified_by_user else '' kwargs['initial'] = initial super().__init__(*args, **kwargs) current_user = self.request.user self.fields[ 'application_roles'].queryset = current_user.get_administrable_application_roles( ) # self.fields['role_profiles'].queryset = current_user.get_administrable_role_profiles() self.fields['role_profiles'].choices = [ (role_profile.id, role_profile) for role_profile in current_user.get_administrable_role_profiles() ] self.fields[ 'organisations'].queryset = current_user.get_administrable_user_organisations( ) def save(self): cd = self.cleaned_data current_user = self.request.user # registrationprofile data self.registrationprofile.known_person1_first_name = cd[ 'known_person1_first_name'] self.registrationprofile.known_person1_last_name = cd[ 'known_person1_last_name'] self.registrationprofile.known_person2_first_name = cd[ 'known_person2_first_name'] self.registrationprofile.known_person2_last_name = cd[ 'known_person2_last_name'] self.registrationprofile.save() # user data self.user.username = cd['username'] self.user.first_name = cd['first_name'] self.user.last_name = cd['last_name'] self.user.is_stored_permanently = cd['is_stored_permanently'] if cd['notes']: UserNote.objects.create_note(user=self.user, notes=[cd['notes']], created_by_user=current_user) # userprofile data self.update_user_m2m_fields('organisations', current_user) self.update_user_m2m_fields('application_roles', current_user) self.update_user_m2m_fields('role_profiles', current_user) organisation = self.cleaned_data['organisations'] if is_validation_period_active(organisation): # a new registered user is valid_until from now for the validation period self.user.valid_until = now() + datetime.timedelta( days=settings.SSO_VALIDATION_PERIOD_DAYS) self.user.save() return self.registrationprofile
class UserSelfRegistrationForm(forms.Form): """ used in for the user self registration """ error_messages = { 'duplicate_username': _("A user with that username already exists."), 'duplicate_email': _("A user with that email address already exists."), } first_name = forms.CharField( label=_('First name'), required=True, max_length=30, widget=bootstrap.TextInput( attrs={'placeholder': capfirst(_('first name'))})) last_name = forms.CharField( label=_('Last name'), required=True, max_length=30, widget=bootstrap.TextInput( attrs={'placeholder': capfirst(_('last name'))})) email = forms.EmailField(label=_('Email'), required=True, widget=bootstrap.EmailInput()) picture = Base64ImageField( label=_('Your picture'), help_text= _('Please use a photo of your face. We are using it also to validate your registration.' ), widget=bootstrap.ClearableBase64ImageWidget( attrs={ 'max_file_size': User.MAX_PICTURE_SIZE, 'width': User.PICTURE_WIDTH, 'height': User.PICTURE_HEIGHT, })) known_person1_first_name = forms.CharField(label=_("First name"), max_length=100, widget=bootstrap.TextInput()) known_person1_last_name = forms.CharField(label=_("Last name"), max_length=100, widget=bootstrap.TextInput()) known_person2_first_name = forms.CharField(label=_("First name"), max_length=100, widget=bootstrap.TextInput()) known_person2_last_name = forms.CharField(label=_("Last name"), max_length=100, widget=bootstrap.TextInput()) about_me = forms.CharField( label=_('About me'), required=False, help_text= _('If you would like to tell us something about yourself, please do so in this box.' ), widget=bootstrap.Textarea(attrs={ 'cols': 40, 'rows': 5 })) country = forms.ModelChoiceField( queryset=Country.objects.filter(active=True), label=_("Country"), widget=bootstrap.Select2()) city = forms.CharField(label=_("City"), max_length=100, widget=bootstrap.TextInput()) language = forms.ChoiceField( label=_("Language"), required=False, choices=(BLANK_CHOICE_DASH + sorted(list(settings.LANGUAGES), key=lambda x: x[1])), widget=bootstrap.Select2()) timezone = forms.ChoiceField( label=_("Timezone"), required=False, choices=BLANK_CHOICE_DASH + list(zip(pytz.common_timezones, pytz.common_timezones)), widget=bootstrap.Select2()) gender = forms.ChoiceField(label=_('Gender'), required=False, choices=(BLANK_CHOICE_DASH + User.GENDER_CHOICES), widget=bootstrap.Select()) dob = forms.DateField(label=_('Date of birth'), required=False, widget=bootstrap.SelectDateWidget( years=range(datetime.datetime.now().year - 100, datetime.datetime.now().year + 1))) def clean_email(self): # Check if email is unique, email = self.cleaned_data["email"] try: get_user_model().objects.get_by_email(email) except ObjectDoesNotExist: return email raise forms.ValidationError(self.error_messages['duplicate_email']) def clean(self): """ if the user clicks the edit_again button a ValidationError is raised, to display the form again. (see post_post method in FormPreview) """ edit_again = self.data.get("_edit_again") if edit_again: raise forms.ValidationError('_edit_again', '_edit_again') return super().clean() @staticmethod def save_data(data, username_generator=default_username_generator): new_user = get_user_model()() new_user.username = username_generator(data.get('first_name'), data.get('last_name')) new_user.first_name = data.get('first_name') new_user.last_name = data.get('last_name') new_user.language = data.get('language') new_user.timezone = data.get('timezone') new_user.gender = data.get('gender') new_user.dob = data.get('dob') new_user.is_active = False new_user.set_unusable_password() if 'picture' in data: new_user.picture = data.get('picture') new_user.save() new_user.create_primary_email(email=data.get('email')) user_address = UserAddress() user_address.primary = True user_address.user = new_user user_address.address_type = 'home' user_address.country = data['country'] user_address.city = data['city'] user_address.addressee = "%s %s" % (data.get('first_name'), data.get('last_name')) user_address.save() registration_profile = RegistrationProfile.objects.create( user=new_user) registration_profile.about_me = data['about_me'] registration_profile.known_person1_first_name = data[ 'known_person1_first_name'] registration_profile.known_person1_last_name = data[ 'known_person1_last_name'] registration_profile.known_person2_first_name = data[ 'known_person2_first_name'] registration_profile.known_person2_last_name = data[ 'known_person2_last_name'] registration_profile.save() return registration_profile
class GroupEmailForm(BaseForm): email_value = EmailFieldLower(required=True, label=_("Email address"), widget=bootstrap.EmailInput()) permission = forms.ChoiceField(label=_('Permission'), choices=Email.PERMISSION_CHOICES, widget=bootstrap.Select()) is_active = forms.BooleanField(required=False, label=_("Active"), widget=bootstrap.CheckboxInput()) class Meta: model = GroupEmail fields = ['homepage', 'name', 'is_guide_email'] widgets = { 'homepage': bootstrap.TextInput(attrs={'size': 50}), 'name': bootstrap.TextInput(attrs={'size': 50}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: email = self.instance.email self.fields['is_active'].initial = email.is_active self.fields['email_value'].initial = force_str(email) self.fields['permission'].initial = email.permission except ObjectDoesNotExist: self.fields['is_active'].initial = True def clean_email_value(self): """ the new email address must .. """ email_value = self.cleaned_data['email_value'] if Email.objects.filter(email=email_value).exclude( groupemail=self.instance).exists(): msg = _('The email address already exists') raise ValidationError(msg) return email_value def save(self, commit=True): cd = self.changed_data if 'email_value' in cd or 'permission' in cd or 'is_active' in cd: created = False try: email = self.instance.email except ObjectDoesNotExist: email = Email(email_type=GROUP_EMAIL_TYPE) created = True email.is_active = self.cleaned_data['is_active'] email.email = self.cleaned_data['email_value'] email.permission = self.cleaned_data['permission'] email.save() if created: self.instance.email = email instance = super().save(commit) return instance