Skip to content

Commit dc1cee2

Browse files
committed
refactor: rename custom form functions to extended profile form
1 parent c100f04 commit dc1cee2

2 files changed

Lines changed: 66 additions & 66 deletions

File tree

openedx/core/djangoapps/user_api/accounts/api.py

Lines changed: 63 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def update_account_settings(requesting_user, update, username=None):
171171

172172
old_name = _validate_name_change(user_profile, update, field_errors)
173173
old_language_proficiencies = _get_old_language_proficiencies_if_updating(user_profile, update)
174-
custom_form = _get_and_validate_custom_form(update, user, field_errors)
174+
extended_profile_form = _get_and_validate_extended_profile_form(update, user, field_errors)
175175

176176
if field_errors:
177177
raise errors.AccountValidationError(field_errors)
@@ -184,7 +184,7 @@ def update_account_settings(requesting_user, update, username=None):
184184
_update_preferences_if_needed(update, requesting_user, user)
185185
_notify_language_proficiencies_update_if_needed(update, user, user_profile, old_language_proficiencies)
186186
_store_old_name_if_needed(old_name, user_profile, requesting_user)
187-
_update_extended_profile_if_needed(update, user_profile, custom_form)
187+
_update_extended_profile_if_needed(update, user_profile, extended_profile_form)
188188
_update_state_if_needed(update, user_profile)
189189

190190
except PreferenceValidationError as err:
@@ -199,41 +199,39 @@ def update_account_settings(requesting_user, update, username=None):
199199
_send_email_change_requests_if_needed(update, user)
200200

201201

202-
def _get_and_validate_custom_form(update: dict, user, field_errors: dict) -> Optional[forms.Form]:
202+
def _get_and_validate_extended_profile_form(update: dict, user, field_errors: dict) -> Optional[forms.Form]:
203203
"""
204-
Validate the custom form if it exists in the update.
204+
Get and validate the extended profile form if it exists in the update.
205205
206206
Args:
207207
update (dict): The update data containing potential extended_profile fields
208-
user (User): The user instance for whom the custom form is being validated
208+
user (User): The user instance for whom the extended profile form is being validated
209209
field_errors (dict): Dictionary to collect field validation errors
210210
211211
Returns:
212-
Optional[forms.Form]: The validated custom form instance, or None if no custom form is needed
213-
214-
Raises:
215-
None: All exceptions are handled internally and errors are added to field_errors
212+
Optional[forms.Form]: The validated extended profile form instance,
213+
or None if no extended profile form is needed
216214
"""
217215
extended_profile = update.get("extended_profile")
218216
if not extended_profile:
219217
return None
220218

221-
custom_fields_data = _extract_custom_fields_data(extended_profile, field_errors)
222-
if not custom_fields_data:
219+
extended_profile_fields_data = _extract_extended_profile_fields_data(extended_profile, field_errors)
220+
if not extended_profile_fields_data:
223221
return None
224222

225-
custom_form = _get_custom_form_instance(custom_fields_data, user, field_errors)
226-
if not custom_form:
223+
extended_profile_form = _get_extended_profile_form_instance(extended_profile_fields_data, user, field_errors)
224+
if not extended_profile_form:
227225
return None
228226

229-
_validate_custom_form_and_collect_errors(custom_form, field_errors)
227+
_validate_extended_profile_form_and_collect_errors(extended_profile_form, field_errors)
230228

231-
return custom_form
229+
return extended_profile_form
232230

233231

234-
def _extract_custom_fields_data(extended_profile: Optional[list], field_errors: dict) -> dict:
232+
def _extract_extended_profile_fields_data(extended_profile: Optional[list], field_errors: dict) -> dict:
235233
"""
236-
Extract custom fields data from extended_profile structure.
234+
Extract extended profile fields data from extended_profile structure.
237235
238236
Args:
239237
extended_profile (Optional[list]): List of field data dictionaries
@@ -249,7 +247,7 @@ def _extract_custom_fields_data(extended_profile: Optional[list], field_errors:
249247
}
250248
return {}
251249

252-
custom_fields_data = {}
250+
extended_profile_fields_data = {}
253251

254252
for field_data in extended_profile:
255253
if not isinstance(field_data, dict):
@@ -264,40 +262,45 @@ def _extract_custom_fields_data(extended_profile: Optional[list], field_errors:
264262
continue
265263

266264
if field_value is not None:
267-
custom_fields_data[field_name] = field_value
265+
extended_profile_fields_data[field_name] = field_value
268266

269-
return custom_fields_data
267+
return extended_profile_fields_data
270268

271269

272-
def _get_custom_form_instance(
273-
custom_fields_data: dict, user, field_errors: dict
270+
def _get_extended_profile_form_instance(
271+
extended_profile_fields_data: dict, user, field_errors: dict
274272
) -> Optional[forms.Form]:
275273
"""
276-
Get or create a custom form instance with the provided data.
274+
Get or create an extended profile form instance.
275+
276+
Attempts to create a form instance using the configured `REGISTRATION_EXTENSION_FORM`.
277+
If an extended profile model exists, tries to bind to existing user data or creates
278+
a new instance. Handles import errors and missing configurations gracefully.
277279
278280
Args:
279-
custom_fields_data (dict): The custom fields data
280-
user (User): The user instance
281-
field_errors (dict): Dictionary to collect validation errors
281+
extended_profile_fields_data (dict): Extended profile field data to populate the form
282+
user (User): User instance to associate with the extended profile
283+
field_errors (dict): Dictionary to collect validation errors if form creation fails
282284
283285
Returns:
284-
Optional[forms.Form]: The custom form instance or None if creation failed
286+
Optional[forms.Form]: Extended profile form instance with user data, or None if
287+
no extended profile form is configured or creation fails
285288
"""
286289
try:
287-
custom_model = get_extended_profile_model()
288-
if not custom_model:
289-
logger.info("No extended profile model configured")
290-
return None
290+
extended_profile_model = get_extended_profile_model()
291291

292-
try:
293-
existing_instance = custom_model.objects.get(user=user)
294-
except ObjectDoesNotExist:
295-
logger.info("No existing extended profile found for user %s, creating new instance", user.username)
296-
existing_instance = None
292+
kwargs = {}
293+
if not extended_profile_model:
294+
logger.info("No extended profile model configured")
295+
else:
296+
try:
297+
kwargs["instance"] = extended_profile_model.objects.get(user=user)
298+
except ObjectDoesNotExist:
299+
logger.info("No existing extended profile found for user %s, creating new instance", user.username)
297300

298-
custom_form = get_registration_extension_form(data=custom_fields_data, instance=existing_instance)
301+
extended_profile_form = get_registration_extension_form(data=extended_profile_fields_data, **kwargs)
299302

300-
return custom_form
303+
return extended_profile_form
301304

302305
except ImportError as e:
303306
logger.warning("Extended profile model not available: %s", str(e))
@@ -311,22 +314,22 @@ def _get_custom_form_instance(
311314
return None
312315

313316

314-
def _validate_custom_form_and_collect_errors(custom_form: forms.Form, field_errors: dict) -> None:
317+
def _validate_extended_profile_form_and_collect_errors(extended_profile_form: forms.Form, field_errors: dict) -> None:
315318
"""
316-
Validate the custom form and collect any validation errors.
319+
Validate the extended profile form and collect any validation errors.
317320
318321
Args:
319-
custom_form (forms.Form): The custom form to validate
322+
extended_profile_form (forms.Form): The extended profile form to validate
320323
field_errors (dict): Dictionary to collect validation errors
321324
"""
322-
if not custom_form.is_valid():
323-
logger.info("Custom form validation failed with errors: %s", custom_form.errors)
325+
if not extended_profile_form.is_valid():
326+
logger.info("Extended profile form validation failed with errors: %s", extended_profile_form.errors)
324327

325-
for field_name, field_errors_list in custom_form.errors.items():
328+
for field_name, field_errors_list in extended_profile_form.errors.items():
326329
first_error = field_errors_list[0] if field_errors_list else "Unknown error"
327330

328331
field_errors[field_name] = {
329-
"developer_message": f"Error in custom field {field_name}: {first_error}",
332+
"developer_message": f"Error in extended profile field {field_name}: {first_error}",
330333
"user_message": str(first_error),
331334
}
332335

@@ -487,53 +490,50 @@ def _notify_language_proficiencies_update_if_needed(data, user, user_profile, ol
487490

488491

489492
def _update_extended_profile_if_needed(
490-
data: dict, user_profile: UserProfile, custom_form: Optional[forms.Form]
493+
data: dict, user_profile: UserProfile, extended_profile_form: Optional[forms.Form]
491494
) -> None:
492495
"""
493496
Update the extended profile information if present in the data.
494497
495498
This function handles two types of extended profile updates:
496499
1. Updates the user profile meta fields with extended_profile data
497-
2. Saves the custom form data to the extended profile model if valid
500+
2. Saves the extended profile form data to the extended profile model if valid
498501
499502
Args:
500503
data (dict): Dictionary containing the update data, may include 'extended_profile' key
501504
user_profile (UserProfile): The UserProfile instance to update
502-
custom_form (Optional[forms.Form]): The validated custom form containing extended profile data,
503-
or None if no custom form is provided
504-
505-
Raises:
506-
None: All exceptions are handled internally with appropriate logging
505+
extended_profile_form (Optional[forms.Form]): The validated extended profile form
506+
containing extended profile data, or None if no extended profile form is provided
507507
508508
Note:
509509
If 'extended_profile' is present in data, the function will:
510510
- Extract field_name and field_value pairs from extended_profile list
511511
- Update the user_profile.meta dictionary with new values
512512
- Save the updated user_profile
513513
514-
If custom_form is provided and valid, the function will:
514+
If extended_profile_form is provided and valid, the function will:
515515
- Save the form data to the extended profile model
516516
- Associate the model instance with the user if it's a new instance
517517
- Log any errors that occur during the save process
518518
"""
519-
if 'extended_profile' in data:
519+
if "extended_profile" in data:
520520
meta = user_profile.get_meta()
521-
new_extended_profile = data['extended_profile']
521+
new_extended_profile = data["extended_profile"]
522522
for field in new_extended_profile:
523-
field_name = field['field_name']
524-
new_value = field['field_value']
523+
field_name = field["field_name"]
524+
new_value = field["field_value"]
525525
meta[field_name] = new_value
526526
user_profile.set_meta(meta)
527527
user_profile.save()
528528

529-
if custom_form and custom_form.is_valid():
529+
if extended_profile_form:
530530
try:
531-
custom_model = custom_form.save(commit=False)
532-
if not hasattr(custom_model, "user") or custom_model.user is None:
533-
custom_model.user = user_profile.user
534-
custom_model.save()
531+
extended_profile_model = extended_profile_form.save(commit=False)
532+
if not hasattr(extended_profile_model, "user") or extended_profile_model.user is None:
533+
extended_profile_model.user = user_profile.user
534+
extended_profile_model.save()
535535
except Exception as e: # pylint: disable=broad-exception-caught
536-
logger.error("Error saving custom model: %s", e)
536+
logger.error("Error saving extended profile model: %s", e)
537537

538538

539539
def _update_state_if_needed(data, user_profile):

openedx/core/djangoapps/user_api/accounts/serializers.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -587,9 +587,9 @@ def get_extended_profile(user_profile: UserProfile) -> list[dict[str, str]]:
587587
'extended_profile_fields' site configuration.
588588
589589
The function supports two data sources:
590-
1. Custom model: If REGISTRATION_EXTENSION_FORM setting points to a form with
591-
a Meta.model, data is retrieved from that model using model_to_dict()
592-
2. Fallback: JSON data stored in UserProfile.meta field
590+
1. Custom model: If `REGISTRATION_EXTENSION_FORM` setting points to a form with
591+
a `Meta.model`, data is retrieved from that model using `model_to_dict()`
592+
2. Fallback: JSON data stored in `UserProfile.meta` field
593593
594594
Args:
595595
user_profile (UserProfile): The user profile instance to get extended fields from.

0 commit comments

Comments
 (0)