Django,自定义身份验证登录。身份验证失败时如何显示错误消息?

Django,自定义身份验证登录。身份验证失败时如何显示错误消息?,django,forms,authentication,Django,Forms,Authentication,我正在创建一个自定义身份验证登录。除了电子邮件和密码不正确时显示错误消息外,一切似乎都正常 我知道这与我在登录失败时呈现login.html页面有关,并且没有向表单提供尝试登录失败的事实,但我不确定如何将其放入代码中 视图.py from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.shortcuts import

我正在创建一个自定义身份验证登录。除了电子邮件和密码不正确时显示错误消息外,一切似乎都正常

我知道这与我在登录失败时呈现login.html页面有关,并且没有向表单提供尝试登录失败的事实,但我不确定如何将其放入代码中

视图.py

from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect

def login_user(request):

logout(request) #logs out user upon reaching the /login/ page

email = password = ''
if request.POST:
    email = request.POST['email']
    password = request.POST['password']

    user = authenticate(email=email, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('/successful_login/')
        else:
           state = "Your account is not active, please contact the administrator."
    else:
       state = "Your email and/or password were incorrect."

state = "Please log in below..."

context = RequestContext(request, {
    'state': state,
    'email': email,
})

return render_to_response('customauth/login.html', {}, context)


@login_required(login_url='/login/')
def successful_login(request):
   return render_to_response('customauth/successful_login.html');
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)


class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(email,
            password=password,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'


    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin
型号.py

from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect

def login_user(request):

logout(request) #logs out user upon reaching the /login/ page

email = password = ''
if request.POST:
    email = request.POST['email']
    password = request.POST['password']

    user = authenticate(email=email, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('/successful_login/')
        else:
           state = "Your account is not active, please contact the administrator."
    else:
       state = "Your email and/or password were incorrect."

state = "Please log in below..."

context = RequestContext(request, {
    'state': state,
    'email': email,
})

return render_to_response('customauth/login.html', {}, context)


@login_required(login_url='/login/')
def successful_login(request):
   return render_to_response('customauth/successful_login.html');
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)


class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(email,
            password=password,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'


    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin
login.html

<html>
<head>
    <title>Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

    {% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static 'customauth/style.css' %}">
</head>
<body>
<div class="container">    

    <div id="loginbox" class="mainbox col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3"> 

        <!--<div class="row">                
            <div class="iconmelon">
              <object type="image/svg+xml" data="customauth/static/customauth/barbell.svg">Your browser does not support SVG</object>
            </div>
        </div>-->

        <div class="panel panel-default" >
            <div class="panel-heading">
                <div class="panel-title text-center"><b>DATA STRONG</b></div>
            </div>     

            <div class="panel-body" >

            {% if form.errors %}
              <p>Invalid email or password! Please try again.</p>
            {% endif %}

                <form name="form" id="form" class="form-horizontal" enctype="multipart/form-data" method="POST">
                   {% csrf_token %}
                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                        <input id="user" type="text" class="form-control" name="email" value="" placeholder="Email">                                        
                    </div>

                    <div class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                        <input id="password" type="password" class="form-control" name="password" placeholder="Password">
                    </div>

                   <div class="input-group checkbox">
                      <label><input name="remember" type="checkbox">Remember me</label>
                   </div>

                    <div class="form-group">
                        <!-- Button -->
                        <div class="col-sm-12 controls">
                            <button type="submit" class="btn btn-primary pull-right" value="{{ next }}"><i class="glyphicon glyphicon-log-in"></i> Log in</button>                          
                        </div>
                    </div>

                </form>

            </div>    <!-----END OF BOOTSTAP CONTAINER----->                 
        </div>  
    </div>
</div>
</body>
</html>

登录
{%load staticfiles%}
数据强
{%if form.errors%}
无效的电子邮件或密码!请再试一次

{%endif%} {%csrf_令牌%} 记得我吗 登录
您应该首先在forms.py中创建一个注册表,如下所示:

class RegistrationForm(forms.Form):
    email = forms.EmailField(label='Email')
    password = forms.CharField(label='Password', widget=forms.PasswordInput())
然后应导入此表单并将其传递到模板,因此将其添加到视图中:

# import the RegistrationForm (change AppName to the name of you app)
from AppName.forms import RegistrationForm

def login_user(request):
  form = RegistrationForm() # add this
  logout(request)
  email = password = ''

  if request.POST:
    form = RegistrationForm(request.POST) # and add this

   ## rest of the code goes here ##

    context = RequestContext(request, {
        'state': state,
        'email': email,
        'form': form, # pass form to the front-end / template
    })

    return render_to_response('customauth/login.html', {}, context)
并将其设置为您的login.html:

{% if form.errors %}
    {{ form.errors }} <!-- display the form errors if they exist -->
{% endif %}

<!-- display the form -->
<form action="/login" method="post">
    {% csrf_token %}
        {{ form }} <-- this displays all the form fields -->
    <input type="submit" value="Submit" />
</form>
{%if form.errors%}
{{form.errors}}
{%endif%}
{%csrf_令牌%}
{{form}}

您是否创建了登录表单?我没有forms.py文件。我从这篇文章中得到的是,表单验证是必要的……这使得。