Skip to content

Commit

Permalink
feat(user-profile): respect section configurations
Browse files Browse the repository at this point in the history
  • Loading branch information
thejoeejoee committed Nov 12, 2023
1 parent 5dcc4de commit da83a9c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
7 changes: 5 additions & 2 deletions fiesta/apps/accounts/forms/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ def get_form_fields(cls, user: User):
)
all_fields = fields_to_include + cls.Meta.fields
# first all required fields, after them all the rest in original order
return sorted(set(all_fields), key=lambda f: (not UserProfileForm.base_fields[f].required, all_fields.index(f)))
return sorted(
set(all_fields),
key=lambda f: (not ((field := UserProfileForm.base_fields.get(f)) and field.required), all_fields.index(f)),
)

@classmethod
def get_user_configuration(cls, user: User):
Expand Down Expand Up @@ -103,10 +106,10 @@ class Meta:
"interests": ChoicedArrayField,
}

# fields, which are shown independently on section configurations
fields = (
*USER_FIELDS.keys(),
# TODO: think about limiting the choices by country of section, in which is current membership
"nationality",
"university",
"faculty",
"picture",
Expand Down
20 changes: 17 additions & 3 deletions fiesta/apps/accounts/services/user_profile_state_synchronizer.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
from __future__ import annotations

import logging

from django.core.exceptions import ValidationError
from django.forms import model_to_dict

from apps.accounts.forms.profile import UserProfileForm
from apps.accounts.forms.profile import FIELDS_FROM_USER, UserProfileForm
from apps.accounts.models import UserProfile
from apps.sections.models import SectionMembership, SectionsConfiguration

logger = logging.getLogger(__name__)


class UserProfileStateSynchronizer:
"""
Expand All @@ -29,7 +33,15 @@ def on_user_profile_update(profile: UserProfile):
form_class = UserProfileForm.for_user(user=profile.user)
form = form_class(
instance=profile,
data=model_to_dict(profile, form_class._meta.fields, form_class._meta.exclude),
data=model_to_dict(
profile,
form_class.base_fields,
form_class._meta.exclude,
)
| model_to_dict(
profile.user,
FIELDS_FROM_USER,
),
)

# make the form bounded, so it thinks it¨s connected to data
Expand All @@ -41,11 +53,13 @@ def on_user_profile_update(profile: UserProfile):
# for this specific accounts conf, profile is not OK,
# so final state leds to incomplete
final_state = UserProfile.State.INCOMPLETE
logger.info("Profile is not valid: %s", form.errors)

try:
# validate also model itself
profile.full_clean()
except ValidationError:
except ValidationError as e:
logger.info("Profile is not valid: %s", e)
final_state = UserProfile.State.INCOMPLETE

profile.state = final_state
Expand Down

0 comments on commit da83a9c

Please sign in to comment.