Django 自定义身份验证未按预期重定向
Django custom authentication doesn't redirect as expected
来自登录 当我重定向到 Logged_IN 以获取 request.user 它给我错误 'User' object is not iterable. 我认为登录请求未传递给 Logged_IN。
但它适用于登录 View.It 响应 request.user。
在 Index 中,即使我没有登录,它 request.user.is_authenticated() 也始终为真。
我还创建了自定义用户而不是使用默认用户。
这是我的 views.py
from django.shortcuts import render,render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth import authenticate
from signup.forms import AuthenticationForm, RegistrationForm
from django.contrib.auth import login , logout
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.core.urlresolvers import reverse
from .models import User
from django.contrib.auth.decorators import login_required
#@login_required
def Index(request):
if request.user.is_authenticated():
return HttpResponse("Welcome")
else:
return render(request,'signup/index.html',{'form':AuthenticationForm,})
def Signin(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
login(request, user)
#return HttpResponse(request.user)
return HttpResponseRedirect(reverse('signup:logged_in',args=()))
else:
form = AuthenticationForm()
def Signup(request):
return render(request,'signup/signup.html',{'form': RegistrationForm,})
def Logged_IN(request):
if request.user.is_authenticated():
return HttpResponse(request.user)
#return render(request,'signup/user.html',{})
这是我的backends.py
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
#from django.contrib.auth.models import check_password
from django.contrib.auth.models import User
from .models import User
class UserAuthBackend(object):
"""
A custom authentication backend. Allows users to log in using their username.
"""
def authenticate(self, username=None, password=None):
"""
Authentication method
"""
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
这是我的自定义用户 models.py
from __future__ import unicode_literals
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, password, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
if not username:
raise ValueError('The given username must be set')
user = self.model(username=username, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, password, **extra_fields)
def create_superuser(self, username, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(username, password, **extra_fields)
class User(AbstractBaseUser,PermissionsMixin):
def __unicode__(self):
return str(self.username)
username=models.CharField("UserName",max_length=100,unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
id=models.AutoField(primary_key=True)
USERNAME_FIELD='username'
objects = UserManager()
class Meta:
verbose_name = _('User')
verbose_name_plural = _('Users')
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
pass
def get_short_name(self):
"Returns the short name for the user."
pass
HttpResponse
需要一个字符串,或者一个可迭代对象。您收到错误是因为您已经传递了 user
实例。
return HttpResponse(request.user)
Django 尝试迭代 request.user
并且您收到错误,因为模型实例不可迭代。
您可以将视图更改为 return 用户名。
return HttpResponse(request.user.username)
来自登录 当我重定向到 Logged_IN 以获取 request.user 它给我错误 'User' object is not iterable. 我认为登录请求未传递给 Logged_IN。
但它适用于登录 View.It 响应 request.user。
在 Index 中,即使我没有登录,它 request.user.is_authenticated() 也始终为真。
我还创建了自定义用户而不是使用默认用户。
这是我的 views.py
from django.shortcuts import render,render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth import authenticate
from signup.forms import AuthenticationForm, RegistrationForm
from django.contrib.auth import login , logout
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.core.urlresolvers import reverse
from .models import User
from django.contrib.auth.decorators import login_required
#@login_required
def Index(request):
if request.user.is_authenticated():
return HttpResponse("Welcome")
else:
return render(request,'signup/index.html',{'form':AuthenticationForm,})
def Signin(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
login(request, user)
#return HttpResponse(request.user)
return HttpResponseRedirect(reverse('signup:logged_in',args=()))
else:
form = AuthenticationForm()
def Signup(request):
return render(request,'signup/signup.html',{'form': RegistrationForm,})
def Logged_IN(request):
if request.user.is_authenticated():
return HttpResponse(request.user)
#return render(request,'signup/user.html',{})
这是我的backends.py
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
#from django.contrib.auth.models import check_password
from django.contrib.auth.models import User
from .models import User
class UserAuthBackend(object):
"""
A custom authentication backend. Allows users to log in using their username.
"""
def authenticate(self, username=None, password=None):
"""
Authentication method
"""
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
这是我的自定义用户 models.py
from __future__ import unicode_literals
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, password, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
if not username:
raise ValueError('The given username must be set')
user = self.model(username=username, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, password, **extra_fields)
def create_superuser(self, username, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(username, password, **extra_fields)
class User(AbstractBaseUser,PermissionsMixin):
def __unicode__(self):
return str(self.username)
username=models.CharField("UserName",max_length=100,unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
id=models.AutoField(primary_key=True)
USERNAME_FIELD='username'
objects = UserManager()
class Meta:
verbose_name = _('User')
verbose_name_plural = _('Users')
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
pass
def get_short_name(self):
"Returns the short name for the user."
pass
HttpResponse
需要一个字符串,或者一个可迭代对象。您收到错误是因为您已经传递了 user
实例。
return HttpResponse(request.user)
Django 尝试迭代 request.user
并且您收到错误,因为模型实例不可迭代。
您可以将视图更改为 return 用户名。
return HttpResponse(request.user.username)