如何使用表单登录用户?

时间:2015-07-30 10:13:45

标签: django django-forms django-views

forms.py:

from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.text import capfirst
from .models import Classname, Sectionname, Teachername, Attendancename

class AuthenticationForm(forms.Form):
    username = forms.CharField(max_length=20)
    password = forms.CharField(widget=forms.PasswordInput)
    error_messages = {
        'invalid_login': ("Please enter a correct %(username)s and password."
                          "Note that both fields may be case-sensitive."),
        'inactive': ("This account is inactive"),
    }

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username, password=password)

            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        if user.is_active:
            login(self.user)   /** It raises error here... **/
        else:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
                )

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache

views.py:

from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import DeleteView, ListView
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from .models import Classname, Sectionname, Teachername, Attendancename
from .forms import ClassnameForm, SectionnameForm, TeachernameForm, AttendancenameForm, UserForm, PasswordChangeForm, AuthenticationForm

def user_login(request):
    if request.method == 'POST':

        form = AuthenticationForm(request.POST)

        if form.is_valid():
            return HttpResponseRedirect(reverse('student:mains'))
        else:
            print(form.errors)  
    else:
        form = AuthenticationForm()
    return render(request, 'login.html', {'form': form},)

urls.py:

from django.conf.urls import url, patterns
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    url(r'^register/$', views.register, name='register'),
    url(r'^login/$', views.user_login, name='login'),
    url(r'^logout/$', views.user_logout, name='logout'),
    url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'post_change_redirect': '/stu/password_change/done/'}, name="password_change"),
    url(r'^password_change/done/$', auth_views.password_change_done, {'template_name': 'password_change_done.html'}, name="password_change_done"),
    url(r'^restricted/', views.restricted, name='restricted'),
    url(r'^mains/', views.mains, name = 'mains'),
]

我是django身份验证的新手。我正在尝试按照我读过的文档来制作东西。如您所见,我有一个'user_login'视图和'AuthenticationForm'表单。

我想登录用户,但不知道该怎么办?正如我在我看来尝试过但没有奏效。

然后我在'can_login_allowed'表单的方法中尝试了它,但是没有用。

还有其他方法可以实现吗?

请!任何人都可以帮我解决这个问题吗?

提前致谢....

1 个答案:

答案 0 :(得分:1)

login函数将请求作为第一个参数。所以你写了这样的confirm_login_allowed

def confirm_login_allowed(self, request):
        if self.user_cache.is_active:
            login(request,self.user_cache)   
        else:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
                )

并在像这样的视图中调用它

def user_login(request):
    if request.method == 'POST':

        form = AuthenticationForm(request.POST)

        if form.is_valid():
             form.confirm_login_allowed(request)
             return HttpResponseRedirect(reverse('student:mains'))
        else:
             ....

也不要使用干净方法调用confirm_login_allowed方法,因为它没有request