Python 如何管理django内置登录中的错误?
我对我的密码有疑问。如果帐户被禁用,并且cred无效,我会尝试重定向erros,但如果无效,我的代码会这样做,但我想发送json数据,比如Python 如何管理django内置登录中的错误?,python,django,Python,Django,我对我的密码有疑问。如果帐户被禁用,并且cred无效,我会尝试重定向erros,但如果无效,我的代码会这样做,但我想发送json数据,比如无效凭据,但它不会从我的条件发送到任何地方 Views.py class LoginView(View): def get(self, request): return render(request, 'login.html', { 'form': AuthenticationForm }) def post(self,
无效凭据
,但它不会从我的条件发送到任何地方
Views.py
class LoginView(View):
def get(self, request):
return render(request, 'login.html', { 'form': AuthenticationForm })
def post(self, request):
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
user = authenticate(
request,
username=form.cleaned_data.get('username'),
password=form.cleaned_data.get('password')
)
if user is not None:
if user.is_active:
login(request, user)
return redirect('/') # home page
else:
return HttpResponse("A") # account disabled
else:
return HttpResponse("invalid_creds")
url.py
urlpatterns = [
path('', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
path('profile/', views.ProfileView.as_view(), name='profile'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
背景
#LOGIN_REDIRECT_URL = '/account/profile'
LOGOUT_REDIRECT_URL = '/'
html
{%csrf_令牌%}
登录表单
登录
尝试将“return HttpResponse(“invalid_creds”)”移到更高一级,以便以无效形式返回:
编辑:根据coment稍微更改了方法
def LoginView(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
user = authenticate(
request,
username=form.cleaned_data.get('username'),
password=form.cleaned_data.get('password')
)
if user is not None:
if user.is_active:
login(request, user)
return redirect('/') # home page
else:
return HttpResponse("A") # account disabled
else: # this else is one level higher
return HttpResponse("invalid_creds")
return render(request, 'login.html', { 'form': AuthenticationForm })
它保持不变。它只在login.htmlthe中重定向相同,但它似乎仅使用
{{form}
进行验证,是否有方法覆盖它?
def LoginView(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
user = authenticate(
request,
username=form.cleaned_data.get('username'),
password=form.cleaned_data.get('password')
)
if user is not None:
if user.is_active:
login(request, user)
return redirect('/') # home page
else:
return HttpResponse("A") # account disabled
else: # this else is one level higher
return HttpResponse("invalid_creds")
return render(request, 'login.html', { 'form': AuthenticationForm })