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

时间:2020-02-15 12:58:21

标签: django django-views django-authentication django-settings django-database

我在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 %}

1 个答案:

答案 0 :(得分:1)

UserCreationForm [GitHub]已通过flush privileges; ALTER USER root@localhost IDENTIFIED VIA mysql_native_password USING PASSWORD("verysecret")` 设置了密码。确实:

.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