Skip to content

Commit

Permalink
Use custom user model in RegistrationForm
Browse files Browse the repository at this point in the history
By default, Django will use its own default User model when
initializing the CreationForm.

This will cause FieldErrors to be raised when a customer user model
is provided but doesn't contain the same fields as in Django's default
implementation.

That's why we use the custom user model to instantiate a CreationForm
instead. The implementation can now have any fields it wants as long as
it's compatible with Django's AbstractUser.

Fixes ubernostrum#234
  • Loading branch information
confuzeus committed Oct 28, 2022
1 parent 94587a4 commit 65b7315
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
14 changes: 11 additions & 3 deletions docs/custom-user.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ order to do so. If you are using a custom user model, please read this
document thoroughly *before* using django-registration, in order to
ensure you've taken all the necessary steps to ensure support.

Your customer user model **needs** to define two properties:

1. USERNAME_FIELD
2. EMAIL_FIELD

These fields can be the same value. See `Django's AbstractUser <https://github.com/django/django/blob/main/django/contrib/auth/models.py#L334>`_
for an example implementation.

The process for using a custom user model with django-registration can
be summarized as follows:

Expand Down Expand Up @@ -166,7 +174,7 @@ do **not** directly edit django-registration's code):
from mycustomuserapp.models import MyCustomUser
class MyCustomUserForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
model = MyCustomUser
Expand All @@ -184,7 +192,7 @@ class you wrote:
from django.urls import include, path
from django_registration.backends.activation.views import RegistrationView
from mycustomuserapp.forms import MyCustomUserForm
Expand Down Expand Up @@ -233,4 +241,4 @@ Finally, it may sometimes be the case that a given user model requires
a completely custom set of form and view classes to
support. Typically, this will also involve an account-registration
process far enough from what django-registration's built-in workflows
provide that you would be writing your own workflow in any case.
provide that you would be writing your own workflow in any case.
9 changes: 6 additions & 3 deletions src/django_registration/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ class RegistrationForm(UserCreationForm):
"""

class Meta(UserCreationForm.Meta):
fields = [
User.USERNAME_FIELD,
User.get_email_field_name(),
model = User
fields = [User.USERNAME_FIELD]
email_field_name = User.get_email_field_name()
if User.USERNAME_FIELD != email_field_name:
fields.append(email_field_name)
fields += [
"password1",
"password2",
]
Expand Down

0 comments on commit 65b7315

Please sign in to comment.