我正在努力创建自定义身份验证登录。除了在电子邮件和密码不正确时显示错误消息外,一切似乎都有效。
我知道这与登录失败后我对login.html页面的呈现有关,而且没有提供表单,因为尝试登录失败的事实,但我不知道如何去做把它放在我的代码中。
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>
答案 0 :(得分:6)
您应首先在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>