当我重定向到Logged_IN以获取request.user时,它给出了错误'用户'对象不可迭代。我认为登录请求未传递给Logged_IN。
但它在Signin View中运行良好。它响应request.user。
在索引中,即使我没有登录,request.user.is_authenticated()也始终为true。
此外,我创建了自定义用户,而不是使用默认用户。
这是我的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
答案 0 :(得分:2)
HttpResponse
需要一个字符串或一个可迭代的字符串。您收到错误是因为您已通过user
实例。
return HttpResponse(request.user)
Django尝试迭代request.user
并得到错误,因为模型实例不可迭代。
您可以更改视图以返回用户名。
return HttpResponse(request.user.username)