使用电子邮件作为django的用户名

时间:2012-01-24 21:55:11

标签: django

尝试在django中创建用户时遇到以下错误:

>>> email = 'verylongemail@verylongemail.com'
>>> user_object = User.objects.create_user(username=email, email=email, password='password')
Data truncated for column 'username' at row 1

似乎Django对用户名中允许的字符数有限制。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

我必须手动修改auth_user表以使字段更长,然后通过删除@符号和句点(也可能是其他字符,它实际上不是一个很好的解决方案)将电子邮件转换为用户名。然后,您必须编写一个自定义身份验证后端,根据用户的电子邮件而不是用户名对用户进行身份验证,因为您只需要存储用户名以安抚django。

换句话说,不要再使用用户名字段进行身份验证,请使用电子邮件字段并将用户名存储为电子邮件的版本,以使Django满意。

他们对此主题的官方回应是许多网站更喜欢使用auth的用户名。这取决于您是为社区网站制作社交网站还是仅为用户创建私人网站。

答案 1 :(得分:2)

如果您覆盖Django用户的表单,您实际上可以非常优雅地完成此操作。

class CustomUserCreationForm(UserCreationForm):
"""
    The form that handles our custom user creation
    Currently this is only used by the admin, but it 

允许用户稍后自行注册是有意义的     “””     email = forms.EmailField(required = True)     first_name = forms.CharField(required = True)     last_name = forms.CharField(required = True)

class Meta:
    model = User
    fields = ('first_name','last_name','email')

然后在你的backends.py中你可以把

class EmailAsUsernameBackend(ModelBackend):
"""
Try to log the user in treating given username as email.
We do not want superusers here as well
"""

def authenticate(self, username, password):
    try:
        user = User.objects.get(email=username)
        if user.check_password(password):
            if user.is_superuser():
                pass
            else: return user

    except User.DoesNotExist: return None

然后在您的admin.py中,您可以使用

覆盖
class UserCreationForm(CustomUserCreationForm):
"""
    This overrides django's requirements on creating a user

    We only need email, first_name, last_name
    We're going to email the password
"""
def __init__(self, *args, **kwargs):
    super(UserCreationForm, self).__init__(*args, **kwargs)
    # let's require these fields
    self.fields['email'].required       = True
    self.fields['first_name'].required  = True
    self.fields['last_name'].required   = True
    # let's not require these since we're going to send a reset email to start their account
    self.fields['username'].required    = False
    self.fields['password1'].required   = False
    self.fields['password2'].required   = False

我的其他一些修改,但这应该让你走在正确的轨道上。

答案 2 :(得分:1)

You have to modify the username length field这样syncdb将创建正确的长度varchar,您还必须修改AuthenticationForm以允许更大的值,否则您的用户将无法登录。

from django.contrib.auth.forms import AuthenticationForm

AuthenticationForm.base_fields['username'].max_length = 150
AuthenticationForm.base_fields['username'].widget.attrs['maxlength'] = 150
AuthenticationForm.base_fields['username'].validators[0].limit_value = 150