class RegistrationFormNoUserName(RegistrationFormUniqueEmail):
"""
A registration form that only requires the user to enter their e-mail
address and password. The username is automatically generated
This class requires django-registration to extend the
RegistrationFormUniqueEmail
"""
username = forms.CharField(widget=forms.HiddenInput, required=False)
def clean_username(self):
"This function is required to overwrite an inherited username clean"
return self.cleaned_data['username']
def clean(self):
if not self.errors:
self.cleaned_data['username'] = '%s%s' % (self.cleaned_data['email'].split('@',1)[0], User.objects.count())
super(RegistrationFormNoUserName, self).clean()
return self.cleaned_data
Comments
I updated the username generation a little... Didn't really like the solution with the total user count.
#
Actually the code in my last comment was buggy. Working version:
#
The solution above will only work the first time a duplicate is found. For example, if joe@yahoo.com registers, his username will be "joe". If joe@gmail.com tries to register, it will find "joe" and will get a count of 1 and username will be "joe2". However, if joe@hotmail.com tries to register, the local part will be "joe". It will still get a count of 1 and it will try to set username to joe2 and your application will get an error. This is because filter is "username=joe" (thus, not finding "joe2"). A better solution, and one that will prevent this error is:
c = User.objects.filter(username__startswith=localpart).count()
#