我能够成功注册。用户注册后,他们已成功登录。但之后单独登录并不起作用。我已经复制并粘贴了注册代码中的代码,我不知道这里有什么问题。
这里是forms.py:
class UserForm(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput)
class Meta:
model=User
fields=["username","password","email"]
class Login(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput)
class Meta:
model=User
fields=["username","password"]
这是views.py:
class singup(View):
form_class=UserForm
template_name='users/index.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
user=form.save(commit=False)
username=form.cleaned_data['username']
password=form.cleaned_data['password']
user.set_password(password)
user.save()
user=authenticate(username=username,password=password)
if user is not None:
if user.is_active:
login(request,user)
return render(request,'home/index.html',{'username':username})
return render(request, self.template_name, {'form': form})
class loginView(View):
form_class=Login
template_name='users/login.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
login(request,user)
return render(request, 'home/index.html')
return render(request, self.template_name, {'form': form})
HTML code:
"<h1> Sign In</h1>
<div class="container">
{{ form.errors }}
{{ form.non_field_errors }}
<form action="" method="post">
{% csrf_token %}
username <input type="text" name="username" id="username">
<br>
<br>
password <input type="password" name="password" id="password">
<br>
<br>
<input type="submit" value="login">
</form>
</div>"
我认为这里的问题是它没有输入&#34; form.is_valid()&#34; loginView中的部分!!!
答案 0 :(得分:0)
在您的代码中,在通过以下方式验证用户之后:
user = authenticate(username=username, password=password)
您需要添加两张支票,
例如:
if not user:
return False
if not user.is_active:
retuen False
因为,当您通过“身份验证”对用户进行身份验证时如果登录凭据正确,则返回用户对象,否则返回None或AnnonymousUser。
您需要确保登录凭据正确无误。
答案 1 :(得分:0)
检查用于创建用户的方法是User.objects.create_user(username=xxx,password=xxx)
而不是User.objects.create(username=xxx,password=xxx)