2013-05-13 76 views
1

我有一個允許用戶創建用戶帳戶的表單。問題是,無論何時用戶提交已經通過系統的用戶名。表單不會引發錯誤,但當字段丟失時確實會引發錯誤。可有人好心幫我Django的用戶名已經出錯

def Registration(request): 
    form = UserRegistration() 
    if request.method =='POST': 
     form = UserRegistration(request.POST) 
     if form.is_valid(): 
      user = User.objects.create_user(
       username=form.cleaned_data['username'], 
       email=form.cleaned_data['email'], 
       password=form.cleaned_data['password'] 
       ) 
      user.is_active = True 
      user.save() 
      return render(request,'choose.html',{'form':form}) 

    return render(request, 'register.html', {'form': form},) 

我forms.py

class UserRegistration(forms.Form): 
    username = forms.CharField() 
    email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'}) 

    password = forms.CharField(
    widget=forms.PasswordInput(render_value=False) 
    ) 

    def clean(self): 
      cleaned_data = super(UserRegistration, self).clean() 
      username = cleaned_data.get("username") 
      password = cleaned_data.get("password") 

      user = User.objects.filter(username=username) 
      if user : 
       raise forms.ValidationError(
         "That user is already taken , please select another ") 


      return cleaned_data 

我的模板

<form method ="POST"> 
    {% csrf_token %} 


<span id="error">{{form.username.errors}}</span> 
<span id="error2">{{form.email.errors}}</span> 
<span id="error3">{{form.password.errors}}</span> 

{{form.username}} 
{{form.email}} 
{{form.password}} 
    <input type = "submit" value= "save" id="box2"/> 
</form> 
+0

嘗試與'clean_username'相同它應該工作 – karthikr 2013-05-13 02:41:51

+0

@karthikr我試過了clean_username。它仍然不會產生任何錯誤 – donkeyboy72 2013-05-13 02:51:55

回答

3

您應該使用exists [0]方法:

user = User.objects.filter(username=username) 
if user.exists(): 
    raise forms.ValidationError("That user is already taken") 

編輯:

嘗試使用clean_username方法:

class UserRegistration(forms.Form): 
    .... 

    def clean_username(self): 
     username = self.cleaned_data['username'] 
     if User.objects.filter(username=username).exists(): 
      raise forms.ValidationError("That user is already taken") 
     return username 

你可以添加一個測試,以確保它的工作原理:

from django.test import TestCase 

class TestUniqueUsername(TestCase): 

    def test_unique_username(self): 
     User.objects.create(username='test', password='test', email='[email protected]') 
     form = UserCreationForm(data={'username': 'test'}) 
     self.assertFalse(form.is_valid()) 

[0] https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.exists

+0

我試過你的答案,我仍然沒有驗證錯誤 – donkeyboy72 2013-05-13 02:50:47

+0

你需要使用這個答案,並刪除你的自定義清理方法。 – 2013-05-13 04:33:25

+0

@santiagobasulto - 你應該在'clean_username'方法末尾添加'return username'。 – 2013-05-13 04:34:02

0

試試這個代碼

class UserRegistration(forms.Form): 
    username = forms.CharField() 
    email = forms.EmailField(error_messages={'required':'Error Missing Field , Please Fill this Field'}) 

    password = forms.CharField(
     widget=forms.PasswordInput(render_value=False) 
    ) 

    def clean_username(self): 
     cleaned_data = self.cleaned_data 
     username = cleaned_data.get("username") 
     user = User.objects.filter(username=username) 
     if user.count() > 0: 
      raise forms.ValidationError("That user is already taken , please select another ") 
     return username 

這將這樣的伎倆。

+0

我也試過這個答案。我仍然得到相同的錯誤 – donkeyboy72 2013-05-13 02:50:00

+0

請重新檢查您的代碼。這一定會奏效。我在我的許多項目中使用了該代碼,並且在所有這些項目中工作良好。 – 2013-05-13 02:57:28

+1

你不需要'> 0',只需'如果user.count()' – 2013-05-13 04:27:30

相關問題