我在确保我的用户的全名在注册时保存在用户记录中时遇到问题。我正在使用 Django 1.5 和 django-registration 1.0,虽然我之前已经使用 django 和 django-registration 的早期版本完成了这项工作,但我在使用基于类的视图和信号时遇到了麻烦。
用户注册创建一切正常,所以我相当肯定我得到的信号是错误的。
这是我的代码连接的地方,backends.py
:
from django.contrib.sites.models import Site
from app.forms import MyRegistrationForm
from registration import signals
from registration.backends.default.views import RegistrationView
from registration.signals import user_activated
class MyRegistrationView(RegistrationView):
form_class = MyRegistrationForm
def register(self, request, **cleaned_data):
username, email, password, first_name, last_name = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1'], cleaned_data['first_name'], cleaned_data['last_name']
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(
username, email, password, site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request,
first_name=first_name,
last_name=last_name)
return new_user
def create(sender, user, request, **kwargs):
""" Saves the user's full name to the user record. """
user.first_name = first_name
user.last_name = last_name
user.save()
user_activated.connect(create)
如果我确实得到了正确的信号并且我的表格有问题,这里是forms.py
:
attrs_dict = {'class': 'required'}
logger = logging.getLogger(__name__)
class MyRegistrationForm(RegistrationFormTermsOfService):
"""
Custom registration form performs unique email checking to prevent users with the same email address from registering more than once.
"""
def __init__(self, *args, **kwargs):
super(MyRegistrationForm, self).__init__(*args, **kwargs)
# adding custom error messages
self.fields['username'].error_messages = {'required': 'Please enter a username.'}
self.fields['email'].error_messages = {'required': 'Please enter a valid email address.'}
self.fields['first_name'].error_messages = {'required': 'Please enter a first name.'}
self.fields['last_name'].error_messages = {'required': 'Please enter a last name.'}
self.fields['password1'].error_messages = {'required': 'Please enter a password.'}
self.fields['password2'].error_messages = {'required': 'Please confirm your password.'}
logger.debug('Registration form loaded')
def clean_email(self):
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
return self.cleaned_data['email']
first_name = forms.CharField(label="First Name", widget=forms.TextInput(attrs=attrs_dict))
last_name = forms.CharField(label="Last Name", widget=forms.TextInput(attrs=attrs_dict))