gpt4 book ai didi

python - Django 自定义登录页面

转载 作者:太空狗 更新时间:2023-10-29 20:12:14 32 4
gpt4 key购买 nike

我有一个自定义的 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com