如何使用django-registration在注册表单中添加新字段

时间:2016-03-26 16:08:52

标签: python django django-registration

如何在注册表单中添加新字段? 我很难找到,所以我在这里分享

1 个答案:

答案 0 :(得分:1)

- forms.py:

from registration.forms import RegistrationForm

class UserProfileRegistrationForm(RegistrationForm):
    first_name = forms.CharField(max_length=15, label='First name')
    last_name = forms.CharField(max_length=15, label='Last name')
    date_of_birth = forms.DateField(label='Date of birth',
                                    widget=SelectDateWidget(years=[y for y in range(1950,
                                                                                    datetime.datetime.now().year-17)],
                                                            attrs=({'style': 'width: 33%; display: inline-block;'})),)

    class Meta:
        model = UserModel()
        fields = (UsernameField(), "email", 'first_name', 'last_name',
                  'date_of_birth')

- views.py

from registration.views import RegistrationView

class UserProfileRegistration(RegistrationView):
    success_url = '/'
    form_class = UserProfileRegistrationForm

    def register(self, form):
        """
        Implement user-registration logic here.

        """

        User = UserModel()
        user = User.objects.create_user(
            username = form.cleaned_data['username'],
            first_name = form.cleaned_data['first_name'],
            last_name = form.cleaned_data['last_name'],
            email=form.cleaned_data['email'],
            password=form.cleaned_data['password1']
        )

注意:如果您希望用户自动登录,请使用此功能:https://djangosnippets.org/snippets/1547/

- urls.py

from myapp.views import UserProfileRegistration

url(r'^accounts/register/$', UserProfileRegistration.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),

感谢DrJackilD。 参考:https://github.com/macropin/django-registration/issues/73