Django 登录表单不适用于自定义用户模型
Django login form not working for custom user model
我正在使用 Django 1.8 并实现了自定义用户模型。用户注册部分功能 100%;我可以提交一个表单并验证是否创建了用户。但是我在用户登录过程中苦苦挣扎。
登录表单呈现得很好,但是当我输入我已验证的用户名和密码时(通过 Django 管理员验证),我进入 HttpResponse('Form is invalid') 留言。
我已经卡在这上面一两天了。非常感谢任何建议!
accounts/views.py
from django.views.generic import FormView
from django.contrib.auth import authenticate, login
from django.shortcuts import render
from accounts.forms import CustomUserCreationForm, CustomUserLoginForm
from accounts.models import CustomUser
class CustomUserCreateView(FormView):
form_class = CustomUserCreationForm
template_name = 'registration/registration_form.html'
success_url = '/connections/'
def form_valid(self, form):
form.save()
return super(CustomUserCreateView, self).form_valid(form)
class CustomUserLoginView(FormView):
form_class = CustomUserLoginForm
template_name = 'registration/login.html'
success_url = '/success/'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form':form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = authenticate(
username=form.cleaned_data['email'],
password=form.cleaned_data['password'],
)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(success_url)
else:
return HttpResponse('User is not active') # TEMP
else:
return HttpResponse('User does not exist') # TEMP
else:
return HttpResponse('Form is invalid') # TEMP
accounts/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import CustomUser
class CustomUserLoginForm(AuthenticationForm):
model = CustomUser
# TODO - need to provide error message when no user is found
class CustomUserCreationForm(UserCreationForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ('first_name', 'last_name', 'email', 'mobile_number')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('Passwords do not match!')
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
该错误意味着您在 "CustomUserLoginView" 中的 "post" 方法没有 returning HttpResponse,因为您几乎没有 "pass" 而不是 return正确的反应。这是因为在少数情况下您什么都不做,然后到达方法的底部,默认情况下 python functions/methods return None。在一种情况下(当 user.is_active 时),您只 returning HttpResponse。您应该看到您正在传递 "if-else" 的哪个分支。在所有情况下(总是),您必须 return HttpResponse。
玩得开心!
This answer 最终让我找到了解决方法。
在 'post' 方法中,我需要更改行:
form = self.form_class(request.POST)
至:
form = self.form_class(data=request.POST)
最后,我的 CustomUserLoginView 如下所示:
class CustomUserLoginView(FormView):
form_class = AuthenticationForm
template_name = 'registration/login.html'
success_url = '/connections/'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form':form})
def post(self, request, *args, **kwargs):
form = self.form_class(data=request.POST)
if form.is_valid():
user = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(self.success_url)
else:
return HttpResponse('User is not active') # TEMP
else:
return HttpResponse('User does not exist') # TEMP
else:
return HttpResponse('Form is not valid') # TEMP
我正在使用 Django 1.8 并实现了自定义用户模型。用户注册部分功能 100%;我可以提交一个表单并验证是否创建了用户。但是我在用户登录过程中苦苦挣扎。
登录表单呈现得很好,但是当我输入我已验证的用户名和密码时(通过 Django 管理员验证),我进入 HttpResponse('Form is invalid') 留言。
我已经卡在这上面一两天了。非常感谢任何建议!
accounts/views.py
from django.views.generic import FormView
from django.contrib.auth import authenticate, login
from django.shortcuts import render
from accounts.forms import CustomUserCreationForm, CustomUserLoginForm
from accounts.models import CustomUser
class CustomUserCreateView(FormView):
form_class = CustomUserCreationForm
template_name = 'registration/registration_form.html'
success_url = '/connections/'
def form_valid(self, form):
form.save()
return super(CustomUserCreateView, self).form_valid(form)
class CustomUserLoginView(FormView):
form_class = CustomUserLoginForm
template_name = 'registration/login.html'
success_url = '/success/'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form':form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = authenticate(
username=form.cleaned_data['email'],
password=form.cleaned_data['password'],
)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(success_url)
else:
return HttpResponse('User is not active') # TEMP
else:
return HttpResponse('User does not exist') # TEMP
else:
return HttpResponse('Form is invalid') # TEMP
accounts/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import CustomUser
class CustomUserLoginForm(AuthenticationForm):
model = CustomUser
# TODO - need to provide error message when no user is found
class CustomUserCreationForm(UserCreationForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ('first_name', 'last_name', 'email', 'mobile_number')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('Passwords do not match!')
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
该错误意味着您在 "CustomUserLoginView" 中的 "post" 方法没有 returning HttpResponse,因为您几乎没有 "pass" 而不是 return正确的反应。这是因为在少数情况下您什么都不做,然后到达方法的底部,默认情况下 python functions/methods return None。在一种情况下(当 user.is_active 时),您只 returning HttpResponse。您应该看到您正在传递 "if-else" 的哪个分支。在所有情况下(总是),您必须 return HttpResponse。
玩得开心!
This answer 最终让我找到了解决方法。
在 'post' 方法中,我需要更改行:
form = self.form_class(request.POST)
至:
form = self.form_class(data=request.POST)
最后,我的 CustomUserLoginView 如下所示:
class CustomUserLoginView(FormView):
form_class = AuthenticationForm
template_name = 'registration/login.html'
success_url = '/connections/'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form':form})
def post(self, request, *args, **kwargs):
form = self.form_class(data=request.POST)
if form.is_valid():
user = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(self.success_url)
else:
return HttpResponse('User is not active') # TEMP
else:
return HttpResponse('User does not exist') # TEMP
else:
return HttpResponse('Form is not valid') # TEMP