1

创建 UserProfile 模型后。我开始创建登录,但由于 get_user() 错误而卡住了。

例外

 AttributeError: 'LoginForm' object has no attribute 'get_user'

这是我的代码:

更新

class LoginView(FormView):
    form_class = LoginForm
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'login.html'
    success_url = '/'

    def form_valid(self, form):
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(self.request, user)
                return HttpResponseRedirect(self.get_success_url())
        else:        
            return self.form_invalid()

    def form_invalid(self):
        return HttpResponseRedirect(reverse('accounts:login'))

    def get_success_url(self):
        if self.success_url:
            redirect_to = self.success_url
        else:
            redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')

        netloc = urlparse.urlparse(redirect_to)[1]
        if not redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
        elif netloc and netloc != self.request.get_host():
            redirect_to = settings.LOGIN_REDIRECT_URL
        return redirect_to

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        if form.is_valid():
            return self.form_valid(form)
        else:                
            return self.form_invalid()

如何解决这个问题?任何帮助,将不胜感激。我对 Django 1.5 真的很陌生。需要帮忙。

4

1 回答 1

1

[更新]

在原始代码中,作者authenticate在一个名为get_user. 您已经在表单之外执行此操作,因此只需替换form.get_user()user.

我使用不基于类的登录视图,我什至不关心使用 Django 表单实例,但它应该很容易适应:

def signin(request):
    if request.method == 'POST':
        user = authenticate(
            email=request.POST.get('username', '').lower().strip(),
            password= request.POST.get('password', ''),
        )
        if user is None:
            messages.error(request, u'Invalid credentials')
        else:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(request.GET.get('next', '/'))
            else:
                messages.error(request, u'User is not active.')

    return render_to_response('login.html', locals(),      
                       context_instance=RequestContext(request))

[老答案]

为您的表单定义一个 get_user 方法。

未经测试(但应该让你走上正确的道路):

def get_user(self):
    from django.contrib.auth import authenticate
    return authenticate(
            email=self.cleaned_data.get('username', '').lower().strip(),
            password=self.cleaned_data.get('password', ''),
    )            
于 2013-03-09T15:53:56.517 回答