为了从默认的Django用户模型中添加字段first_name
和last_name
(提供您自己的表单类):
将这两个字段添加到默认RegistrationForm
的Meta.fields
中:
from django_registration.forms import RegistrationForm
class RegistrationWithNameForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
fields = ["first_name", "last_name"] + RegistrationForm.Meta.fields
通过在urls.py
中添加路径来覆盖默认的RegistrationView
:
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")),
测试用例:
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)
for field in ["username", "first_name", "last_name", "email"]:
self.assertEqual(self.post_data[field], getattr(user, field))
request.POST
(全部大写)。 - samir105