无法向 django-registration 添加自定义字段 [英] Not able to add custom fields to django-registration
问题描述
我扩展了RegistrationFormUniqueEmail
class CustomRegistrationFormUniqueEmail(RegistrationFormUniqueEmail):
first_name = forms.CharField(label=_('First name'), max_length=30,required=True)
last_name = forms.CharField(label=_('Last name'), max_length=30, required=True)
def save(self, profile_callback=None):
new_user = super(CustomRegistrationFormUniqueEmail, self).save(profile_callback=profile_callback)
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
return new_user
然后改变视图
# form = form_class(data=request.POST, files=request.FILES)
form = CustomRegistrationFormUniqueEmail(data=request.POST, files=request.FILES)
但是,我仍然看到仅包含四个字段的默认表单.
But, still I see default form which contains four fields only.
推荐答案
我们最近实现了这样一个表单.这是我们所做的:
We recently implemented such a form. Here's what we've done:
创建一个新的
backend
(只需从默认后端复制它即可)
Create a new
backend
(just copy it from the default backend to start with)
registration/
backends/
default/
custom/ # <- your new backend
...
在新的urls.py
中调整后端参数
...
{ 'backend': 'registration.backends.custom.DefaultBackend' },
...
在 custom
下创建一个 forms.py
.根据您的喜好调整此表单(字段和验证)
Create a forms.py
under custom
. Adjust this form to your liking (fields and validations)
在 registration/urls.py
中指向正确的后端:
In the registration/urls.py
point to the proper backend:
# from registration.backends.default.urls import *
from registration.backends.custom.urls import *
应该可以.这特别有效,因为:
That should work. Particularly this works because:
您的
custom/__init__.py
将有一个带有get_form_class
方法的DefaultBackend
类:
Your
custom/__init__.py
will have aDefaultBackend
class with aget_form_class
method:
def get_form_class(self, request):
"""
Return the default form class used for user registration.
"""
return RegistrationForm
并且您也在该文件中导入您自己的RegistrationForm
:
from registration.backends.custom.forms import RegistrationForm
这篇关于无法向 django-registration 添加自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!