2013-08-20 40 views
0

我有一個登記表,從UserCreationForm,而我曾與下面覆蓋:類型錯誤時,試圖重寫UserCreationForm

from django.contrib.auth.forms import UserCreationForm 
from django.contrib.auth.models import User 
from django import forms 
import re 
from django.core.exceptions import ObjectDoesNotExist 

class UserCreationForm(UserCreationForm): 


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

    error_messages = { 
     'duplicate_username': _("A user with that email already exists."), 
     'password_mismatch': _("The two password fields didn't match."), 
    }  

    username = forms.EmailField(label='Email', max_length=250, unique=True) 

    def save(self, commit=True): 
     user = super(UserCreationForm, self).save(commit=False) 
     user.email = user.username 
     user.save() 
     return user 

但我得到了一個錯誤:

NameError at /admin/ 
name '_' is not defined 

所以,我不得不導入

from django.utils.translation import gettext as _ 

而且解決了這個問題。但現在,這已得到修復後,(我guess..that是第一個問題的解決方案),我得到另一個錯誤:

TypeError at /admin/ 
__init__() got an unexpected keyword argument 'unique' 

如果我從EmailField刪除「獨一無二」,一切工作正常。那麼,我從表格中刪除unique=true嗎?對於每個用戶名(這裏是其電子郵件地址),它會始終是唯一的,即使我刪除它?還有一件事,是from django.utils.translation import gettext as _錯誤名稱的適合解決方案'_' is not defined ???我是django的新手。任何幫助將不勝感激!謝謝。

回答

1

unique不是forms.EmailField的參數。你猜我在模型領域混淆了它。

你想使用電子郵件字段的用戶名?如果多數民衆贊成的情況下,試試這個:

class UserCreationForm(UserCreationForm): 
    username = forms.EmailField(widget=forms.TextInput(attrs={'maxlength':75}), 
         label=_("Email")) 

併爲您的查詢「名‘_’沒有定義」:

from django.utils.translation import ugettext_lazy as _ 

這是django.contrib.auth.forms代碼。

+0

好吧,它會永遠是獨一無二的嗎? ''django.utils.translation import gettext as _'和'from django.utils.translation import ugettext_lazy as'_' – Robin

+1

字段是否唯一,在定義模型時要確定,而不是在表格。由於您在此處使用auth.User模型,因此它將被小心保留,因爲它的獨特性。我不確定'gettext'和'ugettext_lazy'之間的確切區別,我建議使用它,因爲它已經在django :)中相應的forms.py中使用過。你可以知道更多關於它[這裏](http://stackoverflow.com/questions/4160770/when-shoud-i-use-ugettext-lazy) – Sudipta

+0

好吧!得到它了!猜猜我現在可以繼續了。感謝以及爲好的解釋! – Robin