django - 关于 Django 自定义身份验证和登录的错误?

标签 django

我为我的登录系统创建了一个自定义身份验证后端。当然,当我在 python shell 中尝试时,自定义后端可以工作。但是,当我在服务器中运行它时出现错误。错误显示“此模型中不存在以下字段或者是 m2m 字段:last_login”。我是否需要在客户模型中包含 last_login 字段,或者是否有其他解决方案可以解决该问题?
这是我的示例代码:

In my models.py

class Customer(models.Model):

  yes_or_no = ((True, 'Yes'),(False, 'No'))
  male_or_female = ((True,'Male'),(False,'Female'))

  name = models.CharField(max_length=100)
  email = models.EmailField(max_length=100,blank = False, null = False)
  password = models.CharField(max_length=100)
  gender = models.BooleanField(default = True, choices = male_or_female)
  birthday = models.DateField(default =None,blank = False, null = False)
  created = models.DateTimeField(default=datetime.now, blank=True)
  _is_active = models.BooleanField(default = False,db_column="is_active")

  @property
  def is_active(self):
    return self._is_active
  # how to call setter method, how to pass value ?
  @is_active.setter
  def is_active(self,value):
    self._is_active = value

  def __str__(self):
    return self.name

在后端.py
from .models import Customer
from django.conf import settings

class CustomerAuthBackend(object):

    def authenticate(self, name=None, password=None):
        try:
            user = Customer.objects.get(name=name)

            if password == getattr(user,'password'):
                # Authentication success by returning the user
                user.is_active = True
                return user
            else:
                # Authentication fails if None is returned
                return None
        except Customer.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return Customer.objects.get(pk=user_id)
        except Customer.DoesNotExist:
            return None

在views.py
@login_required(login_url='/dataInfo/login/')
def login_view(request):
    if request.method == 'POST':

        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(name=username,password=password)
        if user is not None:

            if user.is_active:
                login(request,user)
                #redirect to user profile
                print "suffcessful login!"
                return HttpResponseRedirect('/dataInfo/userprofile')
            else:
                # return a disable account
                return HttpResponse("User acount or password is incorrect")
        else:
            # Return an 'invalid login' error message.
            print "Invalid login details: {0}, {1}".format(username, password)
            # redirect to login page
            return HttpResponseRedirect('/dataInfo/login')
    else:

        login_form = LoginForm()
    return render_to_response('dataInfo/login.html', {'form': login_form}, context_instance=RequestContext(request))

在设置.py
AUTHENTICATION_BACKENDS = ('dataInfo.backends.CustomerAuthBackend', 'django.contrib.auth.backends.ModelBackend',)

最佳答案

发生这种情况是因为您使用的是 django 的 login() 登录用户的功能。
Django 的login函数发出一个名为 user_logged_in 的信号与 user您作为参数提供的实例。 See login() source .
而这个信号在 django 的 contrib.auth.models 中被监听.它尝试更新名为 last_login 的字段假设您提供的用户实例是 django 默认 AbstractUser 的子类模型。
为了解决此问题,您可以执行以下操作之一:

  • 停止使用 login() django 附带的函数并创建一个自定义函数。
  • 断开 user_logged_in来自 update_last_login 的信号接收者。 Read how .
  • 添加一个名为 last_login 的字段根据您的型号
  • 从 django 的基本身份验证模型扩展您的模型。 Read how
  • 关于django - 关于 Django 自定义身份验证和登录的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38156681/

    相关文章:

    django - pip 安装 : How to force a specific package version

    django - ForeignKey 字段不会出现在 Django 管理站点中

    数据库规范化和用户定义的数据存储

    jquery - 使用 Django/Python 将批量 .csv 数据上传到 webapp 的好方法是什么?

    python - (Django) OperationalError at/no such column : minishop_app_products. user_id

    django - 在 Django 中获取根 url

    python - 上传前在本地进行一些处理

    django - 将 django-haystack 与 django-rest-framework 集成?

    python - 使用 django 捕获网络摄像头图像并上传数据库

    python - Django CONN_MAX_AGE 设置错误