python - 为用户创建自定义登录更改了我的管理员的登录。如何防止这种情况?

标签 python django

我正在创建一个网络应用程序,用户必须在其中自行注册并创建配置文件。我正在使用 Django 提供的“AbstractBaseUser”类,因为我想添加一些其他字段。现在,当用户登录时,我希望登录凭证是手机号码和密码。我为此创建了一个自定义身份验证函数并将其注册到我的 settings.py 中。问题是这改变了我的管理员坐席的登录名,我想保持不变。

我按照教程将自定义字段添加到此 link 的用户

我的模型.py:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import UserManager



class userInfo(AbstractBaseUser):

    email = models.EmailField('Email address', unique=True,)
    Mobile = models.CharField(max_length=15, unique=True,)
    Address = models.CharField(max_length=500)
    Landmark = models.CharField(max_length=50)
    Status = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'Mobile' 

    def __unicode__(self):
        return self.get_username()

登录页面的views.py:

import datetime
from .forms import userInfoForm, LoginForm
from django.shortcuts import render, render_to_response
from .models import userInfo, orderHistory
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext, loader
from django.contrib.auth import login as django_login, authenticate, logout as django_logoutdef Login(request):

"""
Log in view
"""
if request.method == 'POST':
    form = LoginForm(data=request.POST)
    print ("Step 1")
    if form.is_valid():
        print ("Step 2")
        user = authenticate(Mobile=request.POST['username'], password=request.POST['password'])
        print ("Step 3")
        if user is None:
            print("No valid user")
        if user is not None:
            print ("Step 3.10")
            if user.is_active:
                print ("Step 4")
                django_login(request, user)
                print ("Step 5")
                return redirect('/i/Home')
else:
    form = LoginForm()
return render_to_response('loginpage.html', {
    'form': form,
}, context_instance=RequestContext(request))`

表单.py:

from django import forms 
from .models import userInfo, orderHistory  
from django.forms import ModelForm


class LoginForm(forms.Form):
"""
Login form
"""
Mobile = forms.CharField(widget=forms.TextInput)
password = forms.CharField(widget=forms.PasswordInput())

class Meta:
    fields = ['Mobile', 'password']        `

我创建的后端:

from django.conf import settings
from django.contrib.auth.models import check_passwor
from .models import userInfo

class EmailAuthBackend(object):
    """
    A custom authentication backend. Allows users to log in using their            email address.
    """

def authenticate(self, Mobile=None, password=None):
    """
    Authentication method
    """
    try:
        user = userInfo.objects.get(Mobile=Mobile)
        if user.check_password(password):
            return user
    except userInfo.DoesNotExist:
        return None

def get_user(self, user_id):
    try:
        user = userInfo.objects.get(pk=user_id)
        if user.is_active:
            return user
        return None
    except userInfo.DoesNotExist:
        return None

最后是我对 settings.py 所做的更改:

AUTH_USER_MODEL = 'Registration.userInfo'
AUTHENTICATION_BACKENDS = ['Registration.authBackend.EmailAuthBackend', ]

最佳答案

Django 的默认后端是 ('django.contrib.auth.backends.ModelBackend',),这是 Django 管理员正在使用的。插入行时:

AUTHENTICATION_BACKENDS = ['Registration.authBackend.EmailAuthBackend', ]

您正在覆盖默认后端,而不是添加第二个后端选项。将该行更改为:

AUTHENTICATION_BACKENDS = (
    'Registration.authBackend.EmailAuthBackend',
    'django.contrib.auth.backends.ModelBackend',
)

并且您的应用程序应该选择第二个后端。您可能需要根据第一个后端是否成功的逻辑触发第二个后端,请参阅对 Django Multiple Authentication Backend for one project, HOW? 等问题的回复或 the docs here .

关于python - 为用户创建自定义登录更改了我的管理员的登录。如何防止这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30823850/

相关文章:

python - 如何绘制在很长一段时间内每小时发生的行数?

python - Python 项目中的一致版本控制

python - 在Python中重新排列列表中值的位置,而无需编写重复、乏味的代码

python - 对于一个 M2M 关系,条目只能出现一次

python - 无法在我的 Django 应用程序的 models.py 中使用 imageField 显示照片?

django - 使用 Django ORM 进行快速移动平均计算

python - 我的 python 逻辑出了什么问题?

python - 如何为模型中的特定字段创建自定义权限?

django - 通过放置更新获取异常 : Incorrect type. 预期 pk 值,收到字典

python - 为什么我不能在 Django Rest Framework 的 ModelViewSet 上使用 @action 装饰器