django只允许超级用户进行身份验证

时间:2018-02-04 07:58:45

标签: python django authentication login

我遇到django身份验证问题,只有超级用户才能进行身份验证。这是我的模型

#models.py
class UserManager(BaseUserManager):

def create_user(self, username, email, password):
    if not email:
        raise ValueError('Users must have an email address')

    elif not username:
        raise ValueError('Users must have an username')

    user = self.model(
        email=self.normalize_email(email),
        username=username,
    )

    user.set_password(password)
    user.save(using=self._db)
    return user

def create_superuse..................

class User(AbstractBaseUser):
    email = models.EmailField(
    verbose_name='email address',
    max_length=255,
    unique=True,
)
    username = models.CharField(
    verbose_name='username',
    max_length=30,
    unique=True,
)

    phonenumber = PhoneNumberField(verbose_name="phonenumber",max_length=13,
                null=True,unique=True)
    name = models.CharField(max_length=30, blank=True)

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    .............

在我的设置中,我添加了这个。

#settings.py
AUTH_USER_MODEL = 'accounts.User'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'accounts.backends.MyPhonenumberBackend',
)

这是我的后端

#backends.py
from django.contrib.auth import get_user_model

class MyPhonenumberBackend(object):

    def authenticate(self, username=None, password=None):
        my_user_model = get_user_model()
        try:
            user = my_user_model.objects.get(phonenumber=username)
            if user.check_password(password):
                return user
        except my_user_model.DoesNotExist:
            return None
        except:
            return None

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

我的观点

#views.py
def seller_login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password  = request.POST.get('password')

        user = authenticate(username=username,password=password)

        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('home'))

            else:
                return HttpReponse('Account is not active')
        else:
            print('Someone tries to login and failed')
            print('username: {} and password {}'.format(username,password))
            return HttpResponse('Invalid Username and Password')

    else:
        return render(request,'accounts/registered/seller_login.html',{})

我正在使用登录页面的自定义模板

<form method="POST" action="{% url 'accounts:login' %}">
    {% csrf_token %}
    <input type="text" id="login" class="fadeIn second" name="username" placeholder="Email or Phonenumber">
    <input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
    <input type="submit" class="fadeIn fourth" value="Log In">
  </form>

现在当我尝试使用我的超级用户帐户登录时,它可以正常工作,但是当我使用其他用户时,不会发生身份验证(无效的用户名和密码)。我无法弄清楚问题,提前感谢您的帮助并给我时间。

1 个答案:

答案 0 :(得分:0)

在您的观看中尝试此操作

def login_page(request):
    if request.user.is_authenticated:
        return redirect('SOMEWHERE')
    else:
        form = LoginForm(request.POST or None)
        context = {
            "form": form
                  }

        if form.is_valid():
            username  = form.cleaned_data.get("username")
            password  = form.cleaned_data.get("password")
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)


                return redirect(redirect_path)
            else:
                return redirect("SOMEWHERE")
        else:
            # Return an 'invalid login' error message.
            #print("Error")
    return render(request, "students/login.html", context)

这将在forms.py中并将其导入您的视图中。

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)