我有一個允許用戶創建用戶帳戶的表單。問題是,無論何時用戶提交已經通過系統的用戶名。表單不會引發錯誤,但當字段丟失時確實會引發錯誤。可有人好心幫我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>
嘗試與'clean_username'相同它應該工作 – karthikr 2013-05-13 02:41:51
@karthikr我試過了clean_username。它仍然不會產生任何錯誤 – donkeyboy72 2013-05-13 02:51:55