-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathforms.py
More file actions
281 lines (222 loc) · 9.79 KB
/
Copy pathforms.py
File metadata and controls
281 lines (222 loc) · 9.79 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""Forms module for the main app."""
from typing import TYPE_CHECKING, Any
from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Div, Layout, Submit
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django.urls import reverse
from django.utils import timezone
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django_registration.forms import (
RegistrationFormTermsOfService,
RegistrationFormUniqueEmail,
)
from main import models
from .models import Skill, SkillLevel, UserSkill
if TYPE_CHECKING: # pragma: no cover
from .models import User as UserType
def _build_tos_form_label() -> str:
html_anchor = '<a href="{}" target="_blank" rel="noopener noreferrer">'
return format_html(
f"I have read and agree to the {html_anchor} Terms and Conditions</a>"
f" and {html_anchor}Privacy Policy</a>.",
reverse("terms"),
reverse("privacy"),
)
class RegistrationForm(RegistrationFormUniqueEmail, RegistrationFormTermsOfService):
"""Inherit from provided Registration Forms to include additional fields.
This form ensures:
- The email is unique.
- There is a mandatory checkbox to agree to the terms of service and privacy policy.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Override the constructor to include links in the `tos` field label."""
super().__init__(*args, **kwargs)
self.fields["tos"].label = _(_build_tos_form_label())
def clean(self) -> dict[str, Any] | None:
"""Ensure that the Terms are agreed to and assign them to the user instance."""
agreed = self.cleaned_data.get("tos")
if agreed is not True:
raise ValidationError(
{
"tos": _(
"The Terms and Conditions and Privacy Policy must be agreed to."
)
}
)
self.instance.agreed_to_tos = agreed
self.instance.date_agreed = timezone.now()
return super().clean()
class TermsAcceptanceForm(forms.Form):
"""Simple form that requires terms acceptance for existing users."""
tos = forms.BooleanField(required=True)
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Include links to terms and privacy pages in the checkbox label."""
super().__init__(*args, **kwargs)
self.fields["tos"].label = _(_build_tos_form_label())
class UserSkillForm(ModelForm[UserSkill]):
"""Form for user skills."""
class Meta: # noqa: D106
model = UserSkill
fields = ("skill", "skill_level")
class UserSkillsForm(forms.Form):
"""Form for creating UserSkills for all skills in the database."""
def __init__(self, *args: Any, user: "UserType", **kwargs: Any) -> None:
"""Initialize the form with a field for each skill."""
self.user = user
super().__init__(*args, **kwargs)
# Get all skills, ordered by competency for better organization
skills = Skill.objects.select_related(
"competency", "competency__competency_domain"
).order_by("competency__competency_domain__name", "competency__name", "name")
# Get all skill levels for the choice field
skill_levels = SkillLevel.objects.all().order_by("level")
skill_level_choices = [
(level.id, f"{level.level} - {level.name}") for level in skill_levels
]
# Store skill organization data for layout building
skill_organization: dict[str, dict[str, list[Skill]]] = {}
# Create a field for each skill
for skill in skills:
field_name = f"skill_{skill.id}"
# Check if user already has this skill
existing_user_skill = None
if self.user:
try:
existing_user_skill = UserSkill.objects.get(
user=self.user, skill=skill
)
except UserSkill.DoesNotExist:
pass
# Set initial value if user already has this skill
initial_value = (
existing_user_skill.skill_level.id if existing_user_skill else None
)
# Organize skills by competency hierarchy for layout
parent_name = (
skill.competency.competency_domain.name
if skill.competency.competency_domain
else "No Parent"
)
if parent_name not in skill_organization:
skill_organization[parent_name] = {}
if skill.competency.name not in skill_organization[parent_name]:
skill_organization[parent_name][skill.competency.name] = []
skill_organization[parent_name][skill.competency.name].append(skill)
# Create form field with just the skill name as label
self.fields[field_name] = forms.ChoiceField(
choices=[("", "--- Select Level ---"), *skill_level_choices],
required=False,
initial=initial_value,
label="Skill Level",
widget=forms.Select(attrs={"class": "form-select form-select-sm"}),
)
# Set up crispy forms helper
self.helper = FormHelper()
self.helper.form_method = "post"
# Build the layout structure
layout_elements = []
for competency_domain, competencies in skill_organization.items():
# Add parent competency heading
parent_heading = (
f'<h2 class="card-title text-primary mt-5">{competency_domain}</h2>'
)
parent_div = Div(HTML(parent_heading), css_class="mb-5")
competency_elements = []
for competency, skills_list in competencies.items():
# Add competency heading
competency_heading = f"<h4>{competency}</h4>"
# Outer card div
competency_div = Div(css_class="mt-5 card rounded-1")
# Card body div with heading and table
card_body_div = Div(css_class="card-body")
# Add competency heading inside card body
card_body_div.append(HTML(competency_heading))
# Build the table for skills
table_html = """
<table class="table mt-2">
<thead>
<tr>
<th scope="col">Skill</th>
<th scope="col">Description</th>
<th scope="col">Your Level</th>
</tr>
</thead>
<tbody>
"""
for skill in skills_list:
table_html += f"""
<tr>
<td class="fw-semibold">{skill.name}</td>
<td>{skill.description}</td>
<td>{{{{ form.skill_{skill.id} }}}}</td>
</tr>
"""
table_html += """
</tbody>
</table>
"""
# Append table to card body
card_body_div.append(HTML(table_html))
# Add a submit button for this competency
competency_submit = Div(
Submit(
f"submit_{competency.replace(' ', '_')}",
"Save",
css_class="btn btn-primary mt-3",
),
css_class="mt-3",
)
card_body_div.append(competency_submit)
# Append card body to the card
competency_div.append(card_body_div)
# Add the competency div to elements
competency_elements.append(competency_div)
parent_div.extend(competency_elements)
layout_elements.append(parent_div)
# Add submit button
cancel_link = (
"<a href=\"{% url 'profile' %}\" "
'class="btn btn-secondary btn-lg ms-2">Cancel</a>'
)
layout_elements.append(
Div(
Submit(
"submit",
"Save All Skill Assessments",
css_class="btn btn-primary btn-lg",
),
HTML(cancel_link),
css_class="mt-4 pt-3 border-top",
)
)
self.helper.layout = Layout(*layout_elements)
def save(self, user: "UserType") -> tuple[list[UserSkill], list[UserSkill]]:
"""Save the form data as UserSkill instances."""
created_skills = []
updated_skills = []
for field_name, skill_level_id in self.cleaned_data.items():
if field_name.startswith("skill_") and skill_level_id:
skill_id = int(field_name.replace("skill_", ""))
skill = Skill.objects.get(id=skill_id)
skill_level = SkillLevel.objects.get(id=skill_level_id)
# Check if UserSkill already exists
user_skill, created = UserSkill.objects.get_or_create(
user=user, skill=skill, defaults={"skill_level": skill_level}
)
if not created:
# Update existing UserSkill
user_skill.skill_level = skill_level
user_skill.save()
updated_skills.append(user_skill)
else:
created_skills.append(user_skill)
return created_skills, updated_skills
class CreateTeamForm(forms.Form):
"""Form for creating a new team."""
class Meta:
"""Meta options for CreateTeamForm."""
model = models.Team
fields = "__all__"