Python Django登录表单不适用于自定义用户模型

Python Django登录表单不适用于自定义用户模型,python,django,django-registration,Python,Django,Django Registration,我正在使用Django 1.8,并实现了一个自定义用户模型。用户注册件100%可用;我可以提交表单并验证是否创建了用户。但是我在用户登录过程中遇到了困难 登录表单呈现得很好,但是当我输入一个用户名和密码,并且我已经验证了该用户名和密码是否已注册(通过Django admin验证)时,我会看到HttpResponse(“表单无效”)消息 我已经在这上面呆了一两天了。非常感谢您的任何建议 帐户/视图.py from django.views.generic import FormView from

我正在使用Django 1.8,并实现了一个自定义用户模型。用户注册件100%可用;我可以提交表单并验证是否创建了用户。但是我在用户登录过程中遇到了困难

登录表单呈现得很好,但是当我输入一个用户名和密码,并且我已经验证了该用户名和密码是否已注册(通过Django admin验证)时,我会看到HttpResponse(“表单无效”)消息

我已经在这上面呆了一两天了。非常感谢您的任何建议

帐户/视图.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
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
账户/表格.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
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。您只在一种情况下返回HttpResponse(当user.u处于活动状态时)。您应该查看“if-else”的哪个分支。在所有情况下都必须返回HttpResponse(始终)

玩得开心

最终让我找到了解决办法

在“post”方法中,我需要将行更改为:

form = self.form_class(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

嗨,马丁,谢谢你的回答。我已经更新了代码,将HttpResponse对象包含在for every'else'语句中。我还将authenticate值从username=form['username']更改为form['email']。我正在提交一个电子邮件地址和一个密码,我100%确定它们是有效的(它们在Django管理员登录中工作),但我看到“用户不存在”。知道我做错了什么吗?嘿,乔,欢迎你。完美的我不知道,我唯一想改变的是你如何从表格中获得价值。您应该使用“form.cleaned_data['email']”和“form.cleaned_data['password']”。试试看,让我知道:)。谢谢