From a9529af19f3bddfb7677294d2d45cb742db05a98 Mon Sep 17 00:00:00 2001 From: Ben C Date: Tue, 9 Nov 2021 19:51:37 -0500 Subject: [PATCH] Made user setup more user friendly --- CodeReview/settings.py | 2 + Main/templates/form_base.html | 8 +- Main/templatetags/form_tags.py | 12 ++- Users/forms.py | 116 ++++++++++++++++++++- Users/templates/widgets/partial-input.html | 13 +++ Users/views.py | 13 +++ 6 files changed, 155 insertions(+), 9 deletions(-) create mode 100644 Users/templates/widgets/partial-input.html diff --git a/CodeReview/settings.py b/CodeReview/settings.py index 7216b32..29614e5 100644 --- a/CodeReview/settings.py +++ b/CodeReview/settings.py @@ -154,6 +154,7 @@ if DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = 'debug-emails' EMAIL_DOMAIN = "example.com" + EMAIL_ADMIN_DOMAIN = "admin.example.com" else: # If we're not debugging, we use django-mailer to send emails EMAIL_BACKEND = "mailer.backend.DbBackend" @@ -163,6 +164,7 @@ else: EMAIL_HOST_USER = os.getenv("EMAIL_USER", "") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PASS", "") EMAIL_DOMAIN = os.getenv("EMAIL_DOMAIN", "") + EMAIL_ADMIN_DOMAIN = os.getenv("EMAIL_ADMIN_DOMAIN", "") SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER diff --git a/Main/templates/form_base.html b/Main/templates/form_base.html index 40549ab..ae0a584 100644 --- a/Main/templates/form_base.html +++ b/Main/templates/form_base.html @@ -49,9 +49,13 @@ {% csrf_token %} {% for field in form %}
- {% if field in form.visible_fields %} + {% if render_no_floating %} + + {{ field|setup_field:False }} + {% elif field in form.visible_fields %}
- {{ field|setup_field:"form-control" }} + {{ field|setup_field:True }}
diff --git a/Main/templatetags/form_tags.py b/Main/templatetags/form_tags.py index 4ab3013..ad4be3b 100644 --- a/Main/templatetags/form_tags.py +++ b/Main/templatetags/form_tags.py @@ -9,14 +9,14 @@ register = template.Library() @register.filter(name="setup_field") -def setup_field(field: BoundField, classes: str) -> BoundField: +def setup_field(field: BoundField, with_placeholder=True) -> BoundField: """ This filter sets up a field with proper css classes :param field: The field to set up :type field: BoundField - :param classes: Classes to add to the field's element - :type classes: str + :param with_placeholder: Whether to have a placeholder in the input element + :type with_placeholder: bool :returns: The field as html with the added classes :rtype: str """ @@ -30,11 +30,13 @@ def setup_field(field: BoundField, classes: str) -> BoundField: validation_class = "is-valid" attrs = { - 'class': f"{classes} {validation_class}", - 'placeholder': field.label, + 'class': f"form-control {validation_class}", 'aria-describedby': f"{field.name}-feedback" } + if with_placeholder: + attrs['placeholder'] = field.label + new_field = field.as_widget(attrs=attrs) if field.field.show_hidden_initial: diff --git a/Users/forms.py b/Users/forms.py index fddb466..fae1dc1 100644 --- a/Users/forms.py +++ b/Users/forms.py @@ -2,12 +2,97 @@ This file defines the forms used in the Users app """ - -from django.forms import ModelForm +from django.conf import settings +from django.forms import ModelForm, TextInput, CharField, ValidationError from .models import User +class PartialInput(TextInput): + """ + This widget defines a field that utilizes bootstrap's form groups to auto-fill parts of it. + + :cvar template_name: The template this widget renders to + """ + + template_name = "widgets/partial-input.html" + + def __init__(self, *args, **kwargs): + """ + This function is run to instantiate the widget + """ + + self.prefixes = kwargs.get('prefixes', ()) + self.suffixes = kwargs.get('suffixes', ()) + super(PartialInput, self).__init__(*args, **kwargs) + + def format_value(self, value: str) -> str: + """ + This function defines how the widget's value will be rendered to a string + + :param value: The value of the widget + :type value: str + """ + + value = super(PartialInput, self).format_value(value) + if len(self.prefixes) > 0: + value = value[len(''.join(self.prefixes)):] + if len(self.suffixes) > 0: + value = value[:len(''.join(self.suffixes)) * -1] + print(value) + return value + + def get_context(self, name, value, attrs) -> dict: + """ + This function defines additional context to pass to the widget's template + + :param name: The name of the widget + :type name: str + :param value: The value of the widget + :type value: str + :param attrs: The attributes to render in the template + :type attrs: dict + :returns: context to pass to the template + :rtype: dict + """ + + context = super(PartialInput, self).get_context(name, value, attrs) + context['widget']['prefixes'] = self.prefixes + context['widget']['suffixes'] = self.suffixes + return context + + +class PartialField(CharField): + """ + This field utilizes bootstrap's form groups to auto-fill parts of it. + """ + + widget = PartialInput() + + is_admin = False + + def clean(self, value): + """ + This function is run to convert the value to a string + It adds the prefixes and suffixes to the value + + :param value: The value of the field + :type value: str + :returns: The value formatted to an email + :rtype: str + """ + + if not self.is_admin: + value = super(PartialField, self).clean(value) + if len(value) < 3 or len(value) > 3: + raise ValidationError("Please enter 3 digits") + try: + int(value) + except ValueError: + raise ValidationError("Must be a number") + return f'{"".join(self.widget.prefixes)}{value}{"".join(self.widget.suffixes)}' + + class FinishUserForm(ModelForm): """ This form is used to finish setting up a user when syncing them from ActiveDirectory @@ -19,6 +104,10 @@ class FinishUserForm(ModelForm): :cvar model: The model we want the form to edit :cvar fields: The fields on the model we want to edit + :cvar help_texts: The help text to the show for fields + :cvar labels: The label to show for fields + :cvar widgets: The widgets to show for fields + :cvar field_classes: The Field classes to use when rendering fields """ model = User @@ -26,3 +115,26 @@ class FinishUserForm(ModelForm): help_texts = { 'email': "The email you'd like notifications to be sent to (should be a BCTC email)" } + labels = { + 'email': "Email" + } + widgets = { + 'email': PartialInput() + } + field_classes = { + 'email': PartialField + } + + def __init__(self, *args, **kwargs): + """ + This function is used to instantiate a new form + """ + + super(FinishUserForm, self).__init__(*args, **kwargs) + if self.instance.is_superuser: + self.fields['email'].is_admin = True + self.fields['email'].widget.suffixes = (f'@{settings.EMAIL_ADMIN_DOMAIN}',) + else: + self.fields['email'].widget.prefixes = (self.instance.first_name[:3].lower(), self.instance.last_name[:3].lower()) + self.fields['email'].widget.suffixes = (f'@{settings.EMAIL_DOMAIN}',) + self.fields['email'].help_text = "Enter the last 3 digits of your student id" diff --git a/Users/templates/widgets/partial-input.html b/Users/templates/widgets/partial-input.html new file mode 100644 index 0000000..36025fa --- /dev/null +++ b/Users/templates/widgets/partial-input.html @@ -0,0 +1,13 @@ +{% comment %} + This file is used in the PartialInput widget +{% endcomment %} +
+ {% for string in widget.prefixes %} + {{ string }} + {% endfor %} + + {% for string in widget.suffixes %} + {{ string }} + {% endfor %} +
diff --git a/Users/views.py b/Users/views.py index 4bd8887..eed11b5 100644 --- a/Users/views.py +++ b/Users/views.py @@ -46,6 +46,19 @@ class CompleteUserSetupView(LoginRequiredMixin, FormNameMixin, FormAlertMixin, U return User.objects.filter(id=self.request.user.id) + def get_context_data(self, **kwargs) -> dict: + """ + This function defines additional data to pass to the template + It disables placeholders as they mess up input groups + + :returns: context data to pass to the template + :rtype: dict + """ + + context = super(CompleteUserSetupView, self).get_context_data(**kwargs) + context['render_no_floating'] = True + return context + def get(self, request, *args, **kwargs): """ This function is run when the user makes a GET request -- knotmirror 0.0.1