[英]Django login form not working for custom user model
我正在使用Django 1.8,並實現了自定義用戶模型。 用戶注冊件具有100%的功能; 我可以提交表單並驗證是否創建了用戶。 但是我在用戶登錄過程中苦苦掙扎。
登錄表單可以很好地顯示,但是當我輸入已驗證(通過Django管理員驗證)的用戶名和密碼時,我會收到HttpResponse('Form is invalid')消息。
我已經堅持了這一天一兩天。 任何建議,不勝感激!
賬戶/ 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
賬戶/ 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”方法未返回HttpResponse,因為您只有很少的“ pass”而不是返回正確的響應。 這是因為在少數情況下您什么也不做,然后到達方法的底部,並且默認情況下python函數/方法返回None。 在一種情況下(當user.is_active時),您僅返回HttpResponse。 您應該看到您要傳遞“ if-else”的哪個分支。 在所有情況下(總是),您都必須返回HttpResponse。
玩得開心!
這個答案最終使我得以解決。
在“發布”方法中,我需要將行更改為:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.