-
Notifications
You must be signed in to change notification settings - Fork 1
/
profile.py
74 lines (60 loc) 路 2.37 KB
/
profile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from __future__ import annotations
from typing import Type
from django.db.models import Field
from django.forms import Field as FormField, modelform_factory
from django.utils.translation import gettext_lazy as _
from apps.accounts.models import User, UserProfile
from apps.fiestaforms.forms import BaseModelForm
from apps.sections.models import SectionsConfiguration
class UserProfileForm(BaseModelForm):
FIELDS_TO_CONFIGURATION = {
UserProfile.nationality: SectionsConfiguration.required_nationality,
UserProfile.gender: SectionsConfiguration.required_gender,
UserProfile.picture: SectionsConfiguration.required_picture,
}
_FIELD_NAMES_TO_CONFIGURATION = {
f.field.name: conf_field for f, conf_field in FIELDS_TO_CONFIGURATION.items()
}
@classmethod
def for_user(
cls,
user: User,
) -> Type[UserProfileForm]:
"""
Creates the profile form class for specific user.
Fields and configuration are constructed from all AccountsConfigurations from
all sections from all memberships of that specific user.
"""
confs = SectionsConfiguration.objects.filter(
plugin__section__memberships__user=user,
# TODO: check also Membership.state?
)
def callback(f: Field, **kwargs) -> FormField:
if conf_field := cls._FIELD_NAMES_TO_CONFIGURATION.get(f.name):
return f.formfield(
required=any(conf_field.__get__(c) for c in confs), **kwargs
)
return f.formfield(**kwargs)
fields_to_include = tuple(
field_name
for field_name, conf_field in cls._FIELD_NAMES_TO_CONFIGURATION.items()
if any(conf_field.__get__(c) is not None for c in confs)
)
form_klass = modelform_factory(
model=UserProfile,
form=cls,
fields=cls.Meta.fields + fields_to_include,
formfield_callback=callback,
)
return form_klass
class Meta:
model = UserProfile
fields = (
# TODO: think about limiting the choices by country of section, in which is current membership
"home_university",
"home_faculty",
"guest_faculty",
"picture",
)
class UserProfileFinishForm(UserProfileForm):
submit_text = _("Finish Profile")