python - 我的登录表单不起作用,它说在分配之前引用了变量
问题描述
当我转到“/登录”时,出现此错误:
分配前引用的 /login/ 局部变量“表单”处的 UnboundLocalError
这是我的看法:
from django import forms
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
class LoginForm (forms.Form):
username = forms.CharField()
password = forms.CharField()
def login (request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# username = request.POST['username']
# password = request.POST['password']
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(user)
return redirect ("/login/success")
form = LoginForm(request.POST)
return render (request, 'login.html', {'form':form})
这是模板:
{% include 'base.html' %}
{% load crispy_forms_tags %}
<div class="videos">
<form method="post" class="bootstrap4">
{% csrf_token %}
{{ form | crispy }}
<button type="submit" class="btn btn-success">Submit</button>
</form>
Do't have an acount? Click <a href="/register">here</a> to create an account.
</div>
在分配之前我看不到它在哪里被引用,我偶尔会在 python 中遇到这个错误,而且我永远无法在分配之前弄清楚它在哪里被引用。
解决方案
如果request.method
不是POST
,则直接转到
return render (request, 'login.html', {'form':form})
并且form
没有分配。
当您转到 url 时会发生这种情况,因为方法是GET
. 您需要添加else
零件。
def login (request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(user)
return redirect ("/login/success")
else:
form = LoginForm()
return render (request, 'login.html', {'form':form})
推荐阅读
- postgresql - 如何在 postgres 函数中运行合并表
- java - 具有依赖项的 Gradle 自定义插件 jar
- ios - IOS Why Unit Test a class calls ViewController
- php - 在 WordPress 网站中创建 cookie 的问题
- python - 如何缩短代码以生成熊猫数据框?
- java - 没有数组的java随机数生成器
- node.js - socket.io leave current room and join after button is clicked
- java - org.hibernate.MappingException:属性映射在 ENUM 实体中有错误的列数
- algorithm - Longest Substring with no Y Divide and Conquer
- javascript - 确保以前未在注册表中使用过电子邮件