[英]Django custom login page
我有一个自定义的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.')
您可以使用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>
并记住urls.py!
url(r'^login/$','django.contrib.auth.views.login', {'template_name': '/login.html'}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.