Django身份验证函数即使在“设置”中进行必要的更改。

发布于 2025-02-10 13:37:36 字数 10871 浏览 2 评论 0原文

我正在尝试使用Django Python创建登录系统。尽管在其他stackoverflow答案中建议的是在设置中进行某些更改后,即使在设置中进行了某些更改后,验证函数也总是返回。我尝试在Visual Studio代码中以调试模式运行此代码,并发现问题仅在于身份验证功能中,因为它总是没有,因此代码永远无法登录任何用户。

这是我的代码:

  1. views.py(登录函数)
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages

# Create your views here.


def home(request):
    return render(request, 'Home_Page.html')


def signup(request):
    if request.user.is_anonymous:

        if request.method == 'POST':
            if User.objects.filter(username=request.POST.get('username').upper()).exists():
                messages.error(request, 'The username already exists')
            elif User.objects.filter(email=request.POST.get('email').lower()).exists():
                messages.error(request, 'The Email already exists')

            else:

                user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get(
                    'password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'))

                user.save()

                return redirect('home')

        return render(request, 'Signup_Page.html')
    else:
        return redirect('/dashboard')


def login(request):
    if request.user.is_anonymous:
        if request.method == 'POST':
            user = authenticate(username=request.POST.get(
                'username'), password=request.POST.get('password'))
            if user is not None:
                login(request, user)
                return redirect('/dashboard')
            else:

                return render(request, 'Login_Page.html')
        else:
            return render(request, 'Login_Page.html')
    else:
        return redirect('/dashboard')


def logout(request):
    if not request.user.is_anonymous:
        logout(request)

        return HttpResponse("Home Page")
    return redirect('/')

  1. login_page.html

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
  <title>Signin Template for Bootstrap</title>
  <link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/sign-in/">
  <!-- Bootstrap core CSS -->
  <link href="../../dist/css/bootstrap.min.css" rel="stylesheet">

  <style>
    html,
    body {
      height: 100%;
    }
    
    body {
      display: -ms-flexbox;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
      display: -webkit-box;
      display: flex;
      -ms-flex-align: center;
      -ms-flex-pack: center;
      -webkit-box-align: center;
      align-items: center;
      -webkit-box-pack: center;
      justify-content: center;
      padding-top: 40px;
      padding-bottom: 40px;
      background: linear-gradient(to bottom right, rgb(54, 182, 107), rgb(53, 29, 190))
    }
    
    .text-center {
      text-align: center !important;
    }
    
    .btn:not(:disabled):not(.disabled) {
      cursor: pointer;
    }
    
    .btn-block {
      display: block;
      width: 100%;
    }
    
    .btn-group-lg>.btn,
    .btn-lg {
      padding: 0.5rem 1rem;
      font-size: 1.25rem;
      line-height: 1.5;
      border-radius: 0.3rem;
    }
    
    .btn-primary {
      color: #fff;
      background-color: #007bff;
      border-color: #007bff;
    }
    
    .btn {
      display: inline-block;
      font-weight: 400;
      text-align: center;
      white-space: nowrap;
      vertical-align: middle;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      border: 1px solid transparent;
      padding: 0.375rem 0.75rem;
      font-size: 1rem;
      line-height: 1.5;
      border-radius: 0.25rem;
      transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
    }
    
    [type=reset],
    [type=submit],
    button,
    html [type=button] {
      -webkit-appearance: button;
    }
    
    button,
    select {
      text-transform: none;
    }
    
    button,
    input {
      overflow: visible;
    }
    
    button,
    input,
    optgroup,
    select,
    textarea {
      margin: 0;
      font-family: inherit;
      font-size: inherit;
      line-height: inherit;
    }
    
    button {
      border-radius: 0;
    }
    
    *,
     ::after,
     ::before {
      box-sizing: border-box;
    }
    
    .form-signin {
      border-bottom: 1px solid #d2d7da;
      width: 100%;
      max-width: 330px;
      padding: 15px;
      margin: 0 auto;
      background-color: #34B8B0;
      border-radius: 40px
    }
    
    .form-signin .checkbox {
      font-weight: 400;
    }
    
    .form-signin .form-control {
      position: relative;
      box-sizing: border-box;
      height: auto;
      padding: 10px;
      font-size: 16px;
    }
    
    .form-signin .form-control:focus {
      z-index: 2;
    }
    
    .form-signin input[type="text"] {
      margin-bottom: 10px;
      border-bottom-right-radius: 0;
      border-bottom-left-radius: 0;
    }
    
    .form-signin input[type="password"] {
      margin-bottom: 20px;
      border-top-left-radius: 0;
      border-top-right-radius: 0;
    }
    
    .btn-primary {
      color: #fff;
      background-color: #007bff;
      border-color: #007bff;
      border: 2px solid black;
    }
  </style>
</head>

<body class="text-center">
  {% for msg in messages %}
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    {{msg}}

  </div>

  {% endfor %}

  <form class="form-signin" method='POST' action='/login'>
    {% csrf_token %}
    <img class="mb-4" src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
    <h1 class="h3 mb-10 font-weight-normal">Please sign in</h1>
    <input type="text" name='username' id="inputUsername" class="form-control" placeholder="Username" required>
    <input type="password" name='password' id="inputPassword" class="form-control" placeholder="Password" required>
    <br>
    <a style="margin-right: 50%;
                      margin-bottom: 50%;" name='signup' id='signup' href='/forgotpassword'>Forgot password</a>
    <br>
    <button style="margin-top: 4%;
                           margin-bottom: 4%;" class="btn btn-lg btn-primary btn-block" type="submit">
            Sign in
        </button>
    <br>
    <a class='text' name='signup' id='signup' href='/signup'>Create an account</a>
  </form>



</body>

</html>

  1. settings.py
"""
Django settings for DjangoJeeWebsite project.

Generated by 'django-admin startproject' using Django 4.0.4.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-pvq6esb&x2f$%smc$$4m2@%ovybo7sb-qxfz1^q_-j=d%da-_&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Index',
    'Dashboard',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'DjangoJeeWebsite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'DjangoJeeWebsite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

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

I am trying to create a login system with Django python. Though the Authenticate function always returns none even after making certain changes in the settings.py as suggested in other StackOverflow answers. I have tried running this code in debug mode in visual studio code and found out the problem lies in the authenticate function only as it's always none and the code hence is never able to log in any user.

Here is my code:

  1. views.py(login function)
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages

# Create your views here.


def home(request):
    return render(request, 'Home_Page.html')


def signup(request):
    if request.user.is_anonymous:

        if request.method == 'POST':
            if User.objects.filter(username=request.POST.get('username').upper()).exists():
                messages.error(request, 'The username already exists')
            elif User.objects.filter(email=request.POST.get('email').lower()).exists():
                messages.error(request, 'The Email already exists')

            else:

                user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get(
                    'password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'))

                user.save()

                return redirect('home')

        return render(request, 'Signup_Page.html')
    else:
        return redirect('/dashboard')


def login(request):
    if request.user.is_anonymous:
        if request.method == 'POST':
            user = authenticate(username=request.POST.get(
                'username'), password=request.POST.get('password'))
            if user is not None:
                login(request, user)
                return redirect('/dashboard')
            else:

                return render(request, 'Login_Page.html')
        else:
            return render(request, 'Login_Page.html')
    else:
        return redirect('/dashboard')


def logout(request):
    if not request.user.is_anonymous:
        logout(request)

        return HttpResponse("Home Page")
    return redirect('/')

  1. Login_Page.html

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
  <title>Signin Template for Bootstrap</title>
  <link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/sign-in/">
  <!-- Bootstrap core CSS -->
  <link href="../../dist/css/bootstrap.min.css" rel="stylesheet">

  <style>
    html,
    body {
      height: 100%;
    }
    
    body {
      display: -ms-flexbox;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
      display: -webkit-box;
      display: flex;
      -ms-flex-align: center;
      -ms-flex-pack: center;
      -webkit-box-align: center;
      align-items: center;
      -webkit-box-pack: center;
      justify-content: center;
      padding-top: 40px;
      padding-bottom: 40px;
      background: linear-gradient(to bottom right, rgb(54, 182, 107), rgb(53, 29, 190))
    }
    
    .text-center {
      text-align: center !important;
    }
    
    .btn:not(:disabled):not(.disabled) {
      cursor: pointer;
    }
    
    .btn-block {
      display: block;
      width: 100%;
    }
    
    .btn-group-lg>.btn,
    .btn-lg {
      padding: 0.5rem 1rem;
      font-size: 1.25rem;
      line-height: 1.5;
      border-radius: 0.3rem;
    }
    
    .btn-primary {
      color: #fff;
      background-color: #007bff;
      border-color: #007bff;
    }
    
    .btn {
      display: inline-block;
      font-weight: 400;
      text-align: center;
      white-space: nowrap;
      vertical-align: middle;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      border: 1px solid transparent;
      padding: 0.375rem 0.75rem;
      font-size: 1rem;
      line-height: 1.5;
      border-radius: 0.25rem;
      transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
    }
    
    [type=reset],
    [type=submit],
    button,
    html [type=button] {
      -webkit-appearance: button;
    }
    
    button,
    select {
      text-transform: none;
    }
    
    button,
    input {
      overflow: visible;
    }
    
    button,
    input,
    optgroup,
    select,
    textarea {
      margin: 0;
      font-family: inherit;
      font-size: inherit;
      line-height: inherit;
    }
    
    button {
      border-radius: 0;
    }
    
    *,
     ::after,
     ::before {
      box-sizing: border-box;
    }
    
    .form-signin {
      border-bottom: 1px solid #d2d7da;
      width: 100%;
      max-width: 330px;
      padding: 15px;
      margin: 0 auto;
      background-color: #34B8B0;
      border-radius: 40px
    }
    
    .form-signin .checkbox {
      font-weight: 400;
    }
    
    .form-signin .form-control {
      position: relative;
      box-sizing: border-box;
      height: auto;
      padding: 10px;
      font-size: 16px;
    }
    
    .form-signin .form-control:focus {
      z-index: 2;
    }
    
    .form-signin input[type="text"] {
      margin-bottom: 10px;
      border-bottom-right-radius: 0;
      border-bottom-left-radius: 0;
    }
    
    .form-signin input[type="password"] {
      margin-bottom: 20px;
      border-top-left-radius: 0;
      border-top-right-radius: 0;
    }
    
    .btn-primary {
      color: #fff;
      background-color: #007bff;
      border-color: #007bff;
      border: 2px solid black;
    }
  </style>
</head>

<body class="text-center">
  {% for msg in messages %}
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    {{msg}}

  </div>

  {% endfor %}

  <form class="form-signin" method='POST' action='/login'>
    {% csrf_token %}
    <img class="mb-4" src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
    <h1 class="h3 mb-10 font-weight-normal">Please sign in</h1>
    <input type="text" name='username' id="inputUsername" class="form-control" placeholder="Username" required>
    <input type="password" name='password' id="inputPassword" class="form-control" placeholder="Password" required>
    <br>
    <a style="margin-right: 50%;
                      margin-bottom: 50%;" name='signup' id='signup' href='/forgotpassword'>Forgot password</a>
    <br>
    <button style="margin-top: 4%;
                           margin-bottom: 4%;" class="btn btn-lg btn-primary btn-block" type="submit">
            Sign in
        </button>
    <br>
    <a class='text' name='signup' id='signup' href='/signup'>Create an account</a>
  </form>



</body>

</html>

  1. Settings.py
"""
Django settings for DjangoJeeWebsite project.

Generated by 'django-admin startproject' using Django 4.0.4.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-pvq6esb&x2f$%smc$4m2@%ovybo7sb-qxfz1^q_-j=d%da-_&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Index',
    'Dashboard',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'DjangoJeeWebsite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'DjangoJeeWebsite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏末的微笑 2025-02-17 13:37:36

正如@iain Shelvington指出的那样,问题从用用户名设置为uppercase - &gt; 用户名= request.post.get('username')。upper()

user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get('password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'))

然后,您将用户名传递给authenticate()没有upper()

user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))

因此,您可以在创建用户时从用户名中删除upper(),或在authenticate() upper() >。

不过,在附带说明,我看到您有两种称为login()的方法。 django login()和定义的方法login()。这也可能给您带来一些问题。我建议您将定义的login()重命名为:login_view(),因此不会遮盖django login()。例如:

# your defined method here; rename to login_view:
def login_view(request):
     ...
     # so it won't shadow the login method from Django
     login(request, users)
     ...

否则您会收到一个错误:

异常类型:typeerror at/login/except值:login()采用1个位置参数,但给出了2个

您可以看一下此 是否需要更好地了解。

As pointed out by @Iain Shelvington, the issue starts from where a user is being created with the username set to uppercase -> username=request.POST.get('username').upper().

user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get('password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'))

Then the way you're passing the username to the authenticate() is without the upper().

user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))

So you could remove the upper() from the username when creating a user, or add the upper() to the username in the authenticate().

On a side note though, I see where you have two methods called login(). The Django login() and a defined method login(). This might cause a bit of an issue for you as well. I'd suggest that you rename your defined login() to something like: login_view() so it doesn't shadow the Django login(). For example:

# your defined method here; rename to login_view:
def login_view(request):
     ...
     # so it won't shadow the login method from Django
     login(request, users)
     ...

Else you'll get an error like:

Exception Type: TypeError at /login/ Exception Value: login() takes 1 positional argument but 2 were given

You could take a look at this answer to get a better understanding if needs be.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文