我正在使用 django-registration 和 django-profile 来处理注册和配置文件。我想在注册时为用户创建个人资料。我创建了一个自定义注册表单,并使用以下教程将其添加到 urls.py:
教程中的基本思想是覆盖默认注册表单以同时创建配置文件。
forms.py - 在我的个人资料应用中
from django import forms
from registration.forms import RegistrationForm
from django.utils.translation import ugettext_lazy as _
from profiles.models import UserProfile
from registration.models import RegistrationProfile
attrs_dict = { 'class': 'required' }
class UserRegistrationForm(RegistrationForm):
city = forms.CharField(widget=forms.TextInput(attrs=attrs_dict))
def save(self, profile_callback=None):
new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'])
new_profile = UserProfile(user=new_user, city=self.cleaned_data['city'])
new_profile.save()
return new_user
在 urls.py 中
from profiles.forms import UserRegistrationForm
和
url(r'^register/$',
register,
{'backend': 'registration.backends.default.DefaultBackend', 'form_class' : UserRegistrationForm},
name='registration_register'),
显示表格,我可以在城市中输入,但它不会在数据库中保存或创建条目。
最佳答案
您已经成功了——您已经成功构建了一个替换默认表单的自定义表单。但是您正在尝试使用模型表单上的 save() 方法进行自定义处理。这在旧版本的 django-registration 中是可能的,但我可以从您在 URL conf 中指定后端的事实中看出,您使用的是 v0.8。
Previously, the form used to collect data during registration was expected to implement a save() method which would create the new user account. This is no longer the case; creating the account is handled by the backend, and so any custom logic should be moved into a custom backend, or by connecting listeners to the signals sent during the registration process.
换句话说,现在您使用的是 0.8 版,表单上的 save() 方法将被忽略。您需要使用自定义后端或信号进行自定义处理。我选择创建一个自定义后端(如果有人使用信号进行此操作,请发布代码 - 我无法让它以这种方式工作)。您应该能够修改它以保存到您的自定义配置文件中。
- 在您的应用中创建一个 regbackend.py。
- 将 DefaultBackend 中的 register() 方法复制到其中。
- 在方法结束时,进行查询以获取对应的 User 实例。
- 将其他表单字段保存到该实例中。
- 修改 URL conf 使其同时指向自定义表单和自定义后端
所以 URL conf 是:
url(r'^accounts/register/$',
register,
{'backend': 'accounts.regbackend.RegBackend','form_class':MM_RegistrationForm},
name='registration_register'
),
regbackend.py 具有必要的导入,基本上是 DefaultBackend 的副本,只有 register() 方法,并添加了:
u = User.objects.get(username=new_user.username)
u.first_name = kwargs['first_name']
u.last_name = kwargs['last_name']
u.save()
关于python - Django-Registration & Django-Profile,使用你自己的自定义表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2601487/