cha*_*ate 10 python django validation login
我有一个自定义的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)
Run Code Online (Sandbox Code Playgroud)
我试过这个并没有用:这是forms.py
def clean_username(self):
username = self.cleaned_data.get('username')
if not username:
raise forms.ValidationError('username does not exist.')
Run Code Online (Sandbox Code Playgroud)
小智 11
您可以使用Django提供的登录视图.所以你的login.html应该看起来像那个例子.
<form class="login" method="POST" action="/login/">
{% csrf_token %}
{{form.as_p}}
<li><input type="submit" class="logBut" value="Log in"/></li>
</form>
Run Code Online (Sandbox Code Playgroud)
并记住urls.py!
url(r'^login/$','django.contrib.auth.views.login', {'template_name': '/login.html'}),
Run Code Online (Sandbox Code Playgroud)
正确的方法是使用表格,而不是直接从中获取变量request.POST。然后,Django将验证表单数据,并在模板中呈现表单时显示错误。如果需要一个表单字段,那么当该字段为空时,Django将自动显示错误,您甚至不需要为此编写clean_<field_name>方法。
Django已经有一个内置的登录视图。最简单的方法是使用它而不是自己编写。如果您仍然想编写自己的视图,那么查看Django的工作方式仍然很有用。