2012-01-24 35 views
3

我遇到了以下錯誤嘗試在Django創建用戶名:使用電子郵件作爲Django的

>>> email = '[email protected]' 
>>> user_object = User.objects.create_user(username=email, email=email, password='password') 
Data truncated for column 'username' at row 1 

似乎Django的對允許的用戶名字符的數量限制。我將如何解決這個問題?

+1

我剛剛進去修改auth_user表來解決這個問題。 – Brandon

+0

迄今爲止處理它的最好方法。謝謝。 – David542

+0

不客氣。 – Brandon

回答

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 
2

我不得不手動修改auth_user表,使字段變長,然後通過刪除@符號和句點(也許還有其他字符,它確實不是一個好的解決方案)將電子郵件轉換爲用戶名。然後,你必須編寫一個自定義auth後端,根據他們的電子郵件驗證用戶,而不是用戶名,因爲你只需要存儲用戶名來安撫django。

換句話說,不要再使用用戶名字段作爲auth,使用email字段,只需將用戶名存儲爲電子郵件的一個版本,以使Django快樂。

他們對這個主題的官方迴應是,許多網站更喜歡auth的用戶名。這真的取決於你是在製作一個社交網站還是一個私人網站。

+0

+1這是一個恥辱,這是不是內置到Django中,並有一個像'USER_AUTH_FIELD ='EMAIL''這樣的設置,但它實現自己沒有太多問題。請參閱[這裏](http://djangosnippets.org/snippets/74/)示例後端 –

+0

我也這樣做了,但是因爲<1.2不允許在用戶名字段中輸入'@'。現在我寧願修改字段長度而不改變其他任何東西。 –

+0

因此> = 1.2允許在用戶名中輸入「@」?太好了,因爲我不喜歡這樣做。謝謝! – Max

2

如果您覆蓋Django用戶的表單,你可以非常優雅地將其關閉。

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

將使感,讓用戶對自己以後 「」」 電子郵件= forms.EmailField(所需= TRUE) FIRST_NAME = forms.CharField(所需= TRUE) 姓氏=形式註冊。 CharField(所需= 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 

礦有一些其他修改重寫,但這應該讓你在正確的軌道上。