简体   繁体   中英

Django custom authentication doesn't redirect as expected

from Signin When i redirect to Logged_IN to get request.user it gives me error 'User' object is not iterable .i think login request is not passed to Logged_IN.
But it works well with in Signin View.It responses request.user.

In Index it request.user.is_authenticated() is always true even when i dont signed in. Also I have created custom user instead of using default user.

Here is my 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',{})

Here is my 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

Here is my Custom user 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 expects a string, or an iterable. You are getting the error because you have passed the user instance.

return HttpResponse(request.user)

Django tries to iterate over request.user and you get the error because model instances are not iterable.

You could change the view to return the username instead.

return HttpResponse(request.user.username)

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