我有一个自定义的 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提供的登录 View 。所以你的 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'}),
关于python - Django 自定义登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773576/