Skip to content

Forms

hypha.apply.users.forms

User module-attribute

User = get_user_model()

CustomAuthenticationForm

CustomAuthenticationForm(*args, **kwargs)

Bases: AuthenticationForm

Form to collect the email and password for login.

Add "Remember me" checkbox that extends session time.

Adds login extra text and user content to the form, if configured in the wagtail auth settings.

Source code in hypha/apply/users/forms.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.user_settings = AuthSettings.load(request_or_site=self.request)
    self.extra_text = self.user_settings.extra_text
    if self.user_settings.consent_show:
        self.fields["consent"] = forms.BooleanField(
            label=self.user_settings.consent_text,
            help_text=self.user_settings.consent_help,
            required=True,
        )

remember_me class-attribute instance-attribute

remember_me = BooleanField(label=gettext_lazy('Remember me'), help_text=gettext_lazy('On trusted devices only, keeps you logged in for a longer period.'), required=False, widget=CheckboxInput())

user_settings instance-attribute

user_settings = load(request_or_site=request)

extra_text instance-attribute

extra_text = extra_text

PasswordlessAuthForm

PasswordlessAuthForm(*args, **kwargs)

Bases: Form

Form to collect the email for passwordless login or signup (if enabled).

Adds login extra text and user content to the form, if configured in the wagtail auth settings.

Source code in hypha/apply/users/forms.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.request = kwargs.pop("request", None)
    self.user_settings = AuthSettings.load(request_or_site=self.request)
    self.extra_text = self.user_settings.extra_text
    if self.user_settings.consent_show:
        self.fields["consent"] = forms.BooleanField(
            label=self.user_settings.consent_text,
            help_text=self.user_settings.consent_help,
            required=True,
        )

email class-attribute instance-attribute

email = EmailField(label=gettext_lazy('Email address'), required=True, max_length=254, widget=EmailInput(attrs={'autofocus': True, 'autocomplete': 'email'}))

remember_me class-attribute instance-attribute

remember_me = BooleanField(label=gettext_lazy('Remember me'), help_text=gettext_lazy('On trusted devices only, keeps you logged in for a longer period.'), required=False, widget=CheckboxInput())

request instance-attribute

request = pop('request', None)

user_settings instance-attribute

user_settings = load(request_or_site=request)

extra_text instance-attribute

extra_text = extra_text

CustomUserAdminFormBase

CustomUserAdminFormBase(*args, **kwargs)
Source code in hypha/apply/users/forms.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    # HACK: Wagtail admin doesn't work with custom User models that do not have first/last name.
    self.fields["first_name"].widget = forms.HiddenInput(
        attrs={"value": "Not used - see full_name"}
    )
    self.fields["last_name"].widget = forms.HiddenInput(
        attrs={"value": "Not used - see full_name"}
    )

error_messages class-attribute instance-attribute

error_messages = {'duplicate_username': gettext_lazy('A user with that email already exists.'), 'password_mismatch': gettext_lazy("The two password fields didn't match.")}

GroupsModelMultipleChoiceField

Bases: ModelMultipleChoiceField

A custom ModelMultipleChoiceField utilized to provide a custom label for the group prompts

get_group_mmcf classmethod

get_group_mmcf(model_mulitple_choice_field)
Source code in hypha/apply/users/forms.py
@classmethod
def get_group_mmcf(
    cls, model_mulitple_choice_field: forms.ModelMultipleChoiceField
):  # Handle the insertion of group help text
    group_field_dict = model_mulitple_choice_field.__dict__
    queryset = group_field_dict[
        "_queryset"
    ]  # Pull the queryset form the group field
    unneeded_keys = ("empty_label", "_queryset")
    for key in unneeded_keys:
        group_field_dict.pop(
            key, None
        )  # Pop unneeded keys/values, ignore if they don't exist.

    # Overwrite the existing group's ModelMultipleChoiceField with the custom GroupsModelMultipleChoiceField that will provide the help text
    return GroupsModelMultipleChoiceField(queryset=queryset, **group_field_dict)

label_from_instance

label_from_instance(group_obj)

Overwriting ModelMultipleChoiceField's label from instance to provide help_text (if it exists)

Source code in hypha/apply/users/forms.py
def label_from_instance(self, group_obj):
    """
    Overwriting ModelMultipleChoiceField's label from instance to provide help_text (if it exists)
    """
    help_text = getattr(
        roles.registered_roles.get(group_obj.name, {}), "help_text", ""
    )
    if help_text:
        return mark_safe(
            f'{group_obj.name}<p class="group-help-text">{help_text}</p>'
        )
    return group_obj.name

CustomUserEditForm

CustomUserEditForm(*args, **kwargs)

Bases: CustomUserAdminFormBase, UserEditForm

A custom UserEditForm used to provide custom fields (ie. custom group fields)

Source code in hypha/apply/users/forms.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    # Overwrite the existing group's ModelMultipleChoiceField with the custom GroupsModelMultipleChoiceField that will provide the help text
    self.fields["groups"] = GroupsModelMultipleChoiceField.get_group_mmcf(
        self.fields["groups"]
    )

error_messages class-attribute instance-attribute

error_messages = {'duplicate_username': gettext_lazy('A user with that email already exists.'), 'password_mismatch': gettext_lazy("The two password fields didn't match.")}

CustomUserCreationForm

CustomUserCreationForm(register_view=False, request=None, *args, **kwargs)

Bases: CustomUserAdminFormBase, UserCreationForm

Source code in hypha/apply/users/forms.py
def __init__(self, register_view=False, request=None, *args, **kwargs):
    self.request = request
    super().__init__(*args, **kwargs)

    self.user_settings = AuthSettings.load(request_or_site=self.request)
    if register_view and self.user_settings.consent_show:
        self.fields["consent"] = forms.BooleanField(
            label=self.user_settings.consent_text,
            help_text=self.user_settings.consent_help,
            required=True,
        )

    # Overwrite the existing group's ModelMultipleChoiceField with the custom GroupsModelMultipleChoiceField that will provide the help text
    self.fields["groups"] = GroupsModelMultipleChoiceField.get_group_mmcf(
        self.fields["groups"]
    )

error_messages class-attribute instance-attribute

error_messages = {'duplicate_username': gettext_lazy('A user with that email already exists.'), 'password_mismatch': gettext_lazy("The two password fields didn't match.")}

request instance-attribute

request = request

user_settings instance-attribute

user_settings = load(request_or_site=request)

ProfileForm

ProfileForm(*args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/users/forms.py
def __init__(self, *args, **kwargs):
    self.request = kwargs.pop("request", None)
    super().__init__(*args, **kwargs)
    if not self.instance.is_org_faculty:
        del self.fields["slack"]

    if self.request is not None:
        backend = self.request.session["_auth_user_backend"]
        if "social_core.backends" in backend:
            # User is registered with oauth - no password change allowed
            email_field = self.fields["email"]
            email_field.disabled = True
            email_field.required = False
            email_field.help_text = _(
                "You are registered using OAuth, please contact an admin if you need to change your email address."
            )

request instance-attribute

request = pop('request', None)

Meta

model class-attribute instance-attribute
model = User
fields class-attribute instance-attribute
fields = ['full_name', 'email', 'slack']

clean_slack

clean_slack()
Source code in hypha/apply/users/forms.py
def clean_slack(self):
    slack = self.cleaned_data["slack"]
    if slack:
        slack = slack.strip()
        if " " in slack:
            raise forms.ValidationError("Slack names must not include spaces")

        if not slack.startswith("@"):
            slack = "@" + slack

    return slack

clean_email

clean_email()
Source code in hypha/apply/users/forms.py
def clean_email(self):
    email = self.cleaned_data["email"]
    if User.objects.filter(email=email).exists():
        email = (
            self.instance.email
        )  # updated email to avoid email existing message, fix information leak.
    return email

clean_full_name

clean_full_name()
Source code in hypha/apply/users/forms.py
def clean_full_name(self):
    return strip_html_and_nerf_urls(self.cleaned_data["full_name"])

BecomeUserForm

Bases: Form

user_pk class-attribute instance-attribute

user_pk = ModelChoiceField(widget=Select2Widget, help_text=gettext_lazy('Only includes active, non-superusers'), queryset=filter(is_active=True, is_superuser=False), label='', required=False)

EmailChangePasswordForm

EmailChangePasswordForm(user, *args, **kwargs)

Bases: Form

Source code in hypha/apply/users/forms.py
def __init__(self, user, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.user = user

password class-attribute instance-attribute

password = CharField(label=gettext_lazy('Password'), help_text=gettext_lazy('Email change requires you to put password.'), strip=False, widget=PasswordInput(attrs={'autofocus': True}))

user instance-attribute

user = user

clean_password

clean_password()
Source code in hypha/apply/users/forms.py
def clean_password(self):
    password = self.cleaned_data["password"]
    if not self.user.check_password(password):
        raise forms.ValidationError(
            _("Incorrect password. Please try again."),
            code="password_incorrect",
        )
    return password

save

save(updated_email, name, slack, commit=True)
Source code in hypha/apply/users/forms.py
def save(self, updated_email, name, slack, commit=True):
    self.user.full_name = name
    if slack is not None:
        self.user.slack = slack
    if commit:
        self.user.save()
    return self.user

Disable2FAConfirmationForm

Bases: Form

confirmation_text class-attribute instance-attribute

confirmation_text = CharField(label=gettext_lazy('To proceed, type "disable" below and then click on "confirm":'), strip=True, widget=TextInput(attrs={'autofocus': True, 'autocomplete': 'off'}))

clean_confirmation_text

clean_confirmation_text()
Source code in hypha/apply/users/forms.py
def clean_confirmation_text(self):
    text = self.cleaned_data["confirmation_text"]
    if text != "disable":
        raise forms.ValidationError(
            _("Incorrect input."),
            code="confirmation_text_incorrect",
        )
    return text