Closed akhayyat closed 1 year ago
A minimal example Django project reproducing the issue:
https://github.com/akhayyat/django-rest-registration-nested-register-serializer
Here is another potential solution: Use a custom model __init__
method, although this is recommended against in Django docs.
Here is working code: https://github.com/akhayyat/django-rest-registration-nested-register-serializer/tree/fix-using-custom-model-init
@akhayyat thank you for your detailed report. I will look at the issue when I'm back from vacation.
Hi @akhayyat
sorry for the delayed response.
I have evaluated multiple options, my current prefered one is this one, which is a hybrid approach: https://github.com/apragacz/django-rest-registration/pull/269 (details in the description)
It has some downsides, but it looks the best for me now.
The one you proposed: https://github.com/apragacz/django-rest-registration/pull/260 has the advantage of building the user object in the right shape, but relies too much on the database transaction rollback feature (creates unnecessary/risky interactions with the DB).
Let me know what you think about this.
@akhayyat just letting you know: I'm gonna merge #269 and close this issue within few days.
Checklist
Optional checklist
Describe the bug
I am using a custom registration serializer (
REGISTER_SERIALIZER_CLASS
) that has a nested serializer. The nested serializer represents a related object linked through a required (not nullable) foreign key in the user object - each user must be linked to such object.The custom registration serializer has a custom
create()
method that takes care of this: it created the related object first, then passes the related object as the value of the required foreign key field on the user model:However, registration fails before it gets to the
create()
method: it fails during serializer validation, which appears to try to instantiate a user object on its own:rest_registration/utils/validation.py:
which then calls
build_initial_user()
:Expected behavior
Using a registration serializer with a nested serializer should work without errors.
If creating a user object before invoking the serializer is absolutely required, then leverage the registration serializer to create it correctly.
Actual behavior
Registration fails since the serialized attributes that should be consumed by the nested serializer are passed as is to the user model constructor, resulting in an error that looks like this:
Steps to reproduce
Steps to reproduce the behavior:
REGISTER_SERIALIZER_CLASS
Diagnostic info
My
settings.py
: