我写了登录和注册表单,我使用了我的数据库(不是DJANGO的DATABASE)。
档案 models.py :
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
class Student (AbstractBaseUser):
username = models.CharField(max_length=250)
password = models.CharField(max_length=250)
first_name= models.CharField(max_length=250)
last_name= models.CharField(max_length=250)
gender= models.CharField(max_length=250)
telNo = models.CharField(max_length=250)
USERNAME_FIELD = 'username'
def __str__(self):
return self.username
文件 forms.py :
from django import forms
from .models import Student
class SignUpForm(forms.ModelForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
# email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
telNo = forms.CharField(
widget=forms.TextInput(attrs={'style': 'color: black;','placeholder':'تلفن همراه'}),
label='تلفن همراه',
error_messages={'required': "تلفن همراه خود را وارد کنید"})
password = forms.CharField(widget=forms.PasswordInput())
confirm_password = forms.CharField()
class Meta:
model = Student
fields = (
'username', 'first_name', 'last_name', 'telNo',
'password', 'confirm_password'
)
def clean(self):
cleaned_data = super(Student, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
raise forms.ValidationError(
"password and confirm_password does not match"
)
class UserLoginForm(forms.Form):
username = forms.CharField(
widget=forms.TextInput(attrs={'style': 'color: black;','placeholder':'ایمیل یا شماره دانشجویی'}),
label='نام کاربری',
error_messages={'required': "فیلد را پر کنید"})
password = forms.CharField(
widget=forms.PasswordInput(attrs={'style': 'color: black;','placeholder':'رمز عبور'}),
label='رمز عبور',
error_messages={'required': "فیلد را پر کنید"})
文件 views.py :
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
print(user)
auth.login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
def login(request):
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get('username','')
password = form.cleaned_data.get('password','')
stud = Student.objects.get(username=username)
stud.set_password(stud.password)
stud.save()
stud = authenticate(username=username, password=password)
# print(user)
auth.login(request, stud)
return render(request,"registration/login.html",{'form':form})
文件 settings.py :
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'jbja9viev6kskq8()1@m-xh$n91oc!kemw2%a0^#2$=+lxauiv'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
LOGIN_REDIRECT_URL = 'https://www.google.com/'
INSTALLED_APPS = [
'llr.apps.LlrConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'testLogin.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'testLogin.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/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/1.11/howto/static-files/
STATIC_URL = '/static/'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
我不知道为什么会收到错误:
'AnonymousUser' object has no attribute '_meta'
我使用set_password
来获取散列密码。我也会从None
收到authenticate()
。
你能帮助我吗?