如何解决Django Authenticate 方法不适用于扩展“AbstractUser”的 User 类
这是一个简单的视图,我为学院网站的用户做了以下模型:
class User(AbstractUser):
year = models.IntegerField(validators=[MaxValueValidator(4),MinValueValidator(1)],blank=False)
Branch_CHOICES = (
('1','CSE'),('2','ECE'),('3','IT')
)
branch = models.CharField(max_length=3,choices=Branch_CHOICES)
rollNo = models.CharField(validators=[MinLengthValidator(5)],max_length=5,unique=True)
如果需要参考,这是我注册用户的方式(返回的重定向 URL 成功登录用户,但是当我注销并尝试重新登录时,身份验证失败):
def register(request):
if request.method == "POST":
username = request.POST["username"]
rollno = request.POST["rollNo"]
year = request.POST["Year"]
form = registerForm(request.POST)
if form.is_valid():
branch = form.cleaned_data['branch']
else:
return render(request,"events/register.html",{
"message": "You didn't provide all the fields","form": registerForm()
})
email = str(rollno) + '@iiitu.ac.in'
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request,{
"message": "Passwords must match.","form": registerForm()
})
if not username or not rollno or not year or not password:
return render(request,{
"message": "Please enter all the fields","form": registerForm()
})
# Attempt to create new user
try:
user = User.objects.create_user(username,email,password)
user.rollNo = rollno
user.branch = branch
user.year = year
user.save()
except IntegrityError:
return render(request,{
"message": "Username already taken.","form": registerForm()
})
login(request,user)
return HttpResponseRedirect(reverse("events:index"))
else:
ctx = { "form": registerForm() }
return render(request,ctx)
最后,这是我的 login_view:
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request,username=username,password=password)
# Check if authentication successful
if user is not None:
login(request,user)
return HttpResponseRedirect(reverse("events:index"))
else:
return render(request,"events/login.html",{
"message": "Invalid roll number and/or password."
})
else:
return render(request,"events/login.html")
以及我从中获取输入的表单:
<form action="{% url 'events:login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input autofocus class="form-control" type="char" name="username" placeholder="Username">
</div>
<br>
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password">
</div>
<br>
<input class="btn btn-primary" type="submit" value="Login">
</form>
我不知道这里出了什么问题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。