如何在视图中实现AuthenticationForm?

时间:2015-07-29 11:04:00

标签: django django-views django-authentication

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 __init__(self, request=None, *args, **kwargs):
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

        UserModel = get_user_model()
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    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',
                    params={'username': self.username_field.verbose_name},
            )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

     def confirm_login_allowed(self, user):
        if not user.is_active:
            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':
        username = request.POST['username']
        password = request.POST['password']

        form = AuthenticationForm(request, data=request.POST)

        if form.is_valid():
            login(request, user)
            return HttpResponseRedirect(reverse('student:mains'))
        else:
            return HttpResponse("Invalid Login details supplied!")

    return render(request, 'login.html', {'form': form},)       

我的模板:

<html>
<head><title>Login</title></head>
<strong> Mysite Login </strong>
<br><br>
<h3> Please Enter your credentials carefully </h3>
<body>

{% if form.errors %}
    <p>NOT VALID</p>
    {% for errors in form.errors %}
        {{ errors }}
    {% endfor %}
{% endif %}
<form method="post">
    {% csrf_token %}
    <label>Username: </label>
    <input type="text">
    <br>
    <label>Password: </label>
    <input type="password">
    <br>
    <input type="submit" value="Login">
</form>

</body>     
</html>

上面我试图在我当前的应用上实现身份验证。我想在同一个登录页面上显示登录失败错误,我已经为此编写了一个'AuthenticationForm'类。

我阅读了一些文档,但我并不知道如何在我的视图中使用此表单进行身份验证。

请!任何人都可以建议我如何使其正确

0 个答案:

没有答案