在django中创建帐户后无法登录

Posted

技术标签:

【中文标题】在django中创建帐户后无法登录【英文标题】:Not able to login after created account in django 【发布时间】:2020-05-31 00:00:21 【问题描述】:

我在 Django 中创建了登录和注册页面。我无法使用注册时设置的用户名和密码登录。虽然我可以使用超级用户用户名和密码登录。我检查了注册数据是否进入数据库。但是当我尝试登录时,它显示'请输入正确的用户名和密码。两个地方都要注意大小写。'。 请帮忙

models.py-

class userprofileinfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    phone = models.CharField(blank=False,max_length=10)
    hotel_manager = models.BooleanField()
    def __str__(self):
    # Built-in attribute of django.contrib.auth.models.User !
        return self.user.username

views.py-

def HomePage(request):
    if request.user.is_authenticated:
         print('.................................-')
         print(request.user.email)
         return render(request,'homepage.html')
    else:
        print('not online..........................')
        return render(request,'homepage.html')
    return render(request,'homepage.html')

 def register(request):
     registered = False
     if request.method == 'POST':
        user_form = UserCreateForm(data=request.POST)
        profile_form = Formextends(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
           user = user_form.save()
           user.set_password(user.password)
           user.save()
           profile = profile_form.save(commit=False)
           profile.user = user
           profile.save()
           registered = True
           return redirect('/login/')
       else:
           print(user_form.errors,profile_form.errors)
     else:
       user_form = UserCreateForm()
       profile_form = Formextends()

     return render(request,'signup.html',
                      'user_form':user_form,
                       'profile_form':profile_form,
                       'registered':registered)

forms.py-

class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("username","email","password1","password2")
        # ,"phone","hotel_manager")
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["username"].label = "Display name"
        self.fields["email"].label = "Email address"


class Formextends(forms.ModelForm):
    class Meta():
        model = userprofileinfo
        fields = ("phone","hotel_manager")

settings.py-

"""
Django settings for Hotel_Booking_Portal project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ok-r813k26$l9fi8a6w3s0udyc#5n#763e@k^(#5p88%h_kd%*'

# 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',
    'firstapp.apps.FirstappConfig',
    'bootstrap4',
]

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 = 'Hotel_Booking_Portal.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        '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 = 'Hotel_Booking_Portal.wsgi.application'


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

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    



# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
]

AUTH_PASSWORD_VALIDATORS = [
    
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS':'min_length':9
    ,
    
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    ,
]



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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

login.html-

<!DOCTYPE html>
% extends 'base.html' %
% load bootstrap4 %
% block content %
&nbsp
&nbsp
&nbsp
&nbsp
    <div class="container">
      <div class="jumbotron">
    <h1>Login here</h1>
<form method="POST" class="form">
  % csrf_token %
  % bootstrap_form form %
  % buttons %
    <button type="submit" class="btn btn-primary">Login</button>
  % endbuttons %
</form>
</div>
</div>
% endblock %

signup.html-

<!DOCTYPE html>
% extends 'base.html' %
% load bootstrap4 %

% load bootstrap4 %
% block content %
&nbsp
  <div class="container">
    <div class="jumbotron">
  <h2>Create account</h2>
  <form method="POST" class="form">
    % csrf_token %
    % bootstrap_form user_form %
    % bootstrap_form profile_form %
      <button type="submit" class="btn btn-primary">Sign Up</button>
  </form>
  </div>
</div>
% endblock %

【问题讨论】:

UserCreationForm 已经会调用.set_password,所以你不应该再次散列它。 @WillemVanOnsem 非常感谢。它现在正在工作。你能解释一下 UserCreationForm 是如何调用 .set_password 的吗? 查看答案。如您所见(在引用的代码和 GitHub 上),它覆盖了 save 方法,并调用了 .set_password 本身。 【参考方案1】:

UserCreationForm [GitHub] 已经通过.set_password(..) 设置了密码。确实:

class UserCreationForm(forms.ModelForm):
    # …

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

通过在视图中第二次执行此操作,您可以散列散列密码。因此身份验证确实不会成功。在视图中,您可以简单地创建用户:

def register(request):
    if request.method == 'POST':
        user_form = UserCreateForm(data=request.POST)
        profile_form = Formextends(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return redirect('/login/')
        else:
            print((user_form.errors,profile_form.errors))
    else:
        user_form = UserCreateForm()
        profile_form = Formextends()

    return render(
        request,
        'signup.html',
        'user_form': user_form,
         'profile_form': profile_form,
         'registered': False
    )

【讨论】:

以上是关于在django中创建帐户后无法登录的主要内容,如果未能解决你的问题,请参考以下文章

登录 paypal 帐户后无法看到我的应用程序页面

如何停止自动登录到aspnet中创建的帐户

在开发模式下无法在 Xbox One 上登录我的应用沙盒

用户登录后路由到用户帐户

无法从PasswordHasher登录种子的自定义IdentityUser

为啥在 Django 的登录表单中显示错误?