我有一個自定義Django登錄頁面。我想在用戶名或密碼字段爲空時拋出異常。我怎樣才能做到這一點?Django自定義登錄頁面
我view.py登錄方法:
def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
# Gather the username and password provided by the user.
# This information is obtained from the login form.
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
print("auth",str(authenticate(username=username, password=password)))
if user:
# Is the account active? It could have been disabled.
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse("xxx.")
else:
# Bad login details were provided. So we can't log the user in.
print ("Invalid login details: {0}, {1}".format(username, password))
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('user/profile.html', {}, context)
我嘗試這樣做,也沒有工作: 這是forms.py
def clean_username(self):
username = self.cleaned_data.get('username')
if not username:
raise forms.ValidationError('username does not exist.')
可否請您更新正確的縮進 – Sayse
問題只是定義'clean_username(個體經營):如果沒有self.cleaned_data [ '用戶名']:ValidationError( '')在相應的表格'方法。 –
嗨,我把它只是爲了測試,xxx是一個HTML網站。 – chazefate