To add the fields first_name
and last_name
from the default Django User
model provide your own formclass:
Prepend the two fields to Meta.fields
of the default RegistrationForm
:
from django_registration.forms import RegistrationForm
class RegistrationWithNameForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
fields = ["first_name", "last_name"] + RegistrationForm.Meta.fields
Override the default RegistrationView
by adding a path to urls.py
:
from django_registration.backends.activation.views import RegistrationView
from yourapp.forms import RegistrationWithNameForm
path('accounts/register/',
RegistrationView.as_view(form_class=RegistrationWithNameForm),
name='django_registration_register',
),
path("accounts/", include("django_registration.backends.activation.urls")),
Testcase:
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
class RegistrationTestCase(TestCase):
registration_url = reverse("django_registration_register")
test_username = "testuser"
post_data = {
"first_name": "TestFirstName",
"last_name": "TestLastName",
"username": test_username,
"email": "testuser@example.com",
"password1": "mypass",
"password2": "mypass"
}
def test_register(self):
response = self.client.post(self.registration_url, self.post_data)
self.assertRedirects(response, reverse("django_registration_complete"))
user = get_user_model().objects.get(username=self.test_username)
# Assert all fields are present on the newly registered user
for field in ["username", "first_name", "last_name", "email"]:
self.assertEqual(self.post_data[field], getattr(user, field))