Django自定义登录页面 [英] Django custom login page
本文介绍了Django自定义登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义的Django登录页面.我想在用户名或密码字段为空时引发异常.我该怎么办?
I have a custom Django login page. I want to throw an exception when username or password fields are empty. How can I do that?
我的view.py登录方法:
My view.py log in method :
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
I tried this and it didn't work: This is 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应该类似于该示例.
You can use login view, which is provided by Django. So your login.html should look like that example.
<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'}),
这篇关于Django自定义登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文