简体   繁体   中英

Django, custom authentication login. How to display error message when authentication fails?

I'm working on creating a custom authentication login. Everything seems to be working, except the display of an error message when the email and password are incorrect.

I know it has something to do with my rendering of the login.html page upon failure of logging in and not supplying the form with the fact that there was an attempted login failure, but I'm not sure how to go about putting that in my code.

views.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');

models.py

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>

You should first create a Registration Form in forms.py, like this:

class RegistrationForm(forms.Form):
    email = forms.EmailField(label='Email')
    password = forms.CharField(label='Password', widget=forms.PasswordInput())

You should then import and pass this form to your template, so add this to your view:

# 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)

and make this your 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM