После отправки формы регистрации в моем приложении Django я хочу зарегистрировать пользователя.Я хочу, чтобы в качестве имени пользователя использовался адрес электронной почты, указанный в форме.
Для этого я создаю модель CostumUser, для управления этой моделью я также создал CustomUserManager.см. мой models.py:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from .choices import GENDER_CHOICE
# Create your models here.
class CostumUserManager(BaseUserManager):
def _create_user(self, email, firstName, lastName, gender, password, **extra_fields):
"""
Create and save a user with the given email, password, firstname, lastname and gender
"""
if not email:
raise ValueError("The given Email must be set")
email = self.normalize_email(email)
user = self.model(email=email,
first_name=firstName,
last_name=lastName,
gender=gender,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, firstName, lastName, gender, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, firstName, lastName, gender, password, **extra_fields)
def create_superuser(self, email, firstName, lastName, gender, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, firstName, lastName, gender, password, **extra_fields)
class CustomUser(AbstractBaseUser):
#CostumUserManager
objects = CostumUserManager()
#CostumUser fields in db.
email = models.EmailField(max_length=250, unique=True)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
gender = models.CharField(max_length=1, choices= GENDER_CHOICE)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
USERNAME_FIELD = 'email' #Email used as username
#define required fields
REQUIRED_FIELDS = ['first_name','last_name','gender']
def is_staff(self):
return self.staff
def is_actif(self):
return self.actif
Я также создал CustomUserCreationForm.see forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
from .choices import GENDER_CHOICE
class CustomUserCreationForm(UserCreationForm):
first_name = forms.CharField(max_length=40,
widget=forms.TextInput(attrs={'required':True,#set attributes
'class':'form-control',
'placeholder':'First Name *',
})
)
last_name = forms.CharField(max_length=40,
widget=forms.TextInput(attrs={'required':True,#set attributes
'class':'form-control',
'placeholder':'Last Name *',
})
)
email = forms.EmailField(max_length=254,
widget=forms.TextInput(attrs={'required':True,#set attributes
'class':'form-control',
'placeholder':'Your Email *',
})
)
gender = forms.ChoiceField (choices=GENDER_CHOICE,
widget=forms.Select(attrs={'class':'form-control',
}),
initial='Male',
)
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'required':True,#set attributes
'class':'form-control',
'placeholder':'Password *',
}),
strip=False,
)
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'required':True,#set attributes
'class':'form-control',
'placeholder':'Confirm Password *',
}),
strip=False,
)
class Meta(UserCreationForm):
model = CustomUser
fields = ('email','first_name','last_name','gender')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
Мой admin.py выглядит так:
# Register your models here.
# users/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(admin.ModelAdmin):
model = CustomUser
add_form = CustomUserCreationForm
form = CustomUserChangeForm
admin.site.register(CustomUser, CustomUserAdmin)
Когда я пытаюсь зарегистрировать суперпользователя, введите команду:
python manage.py createsuperuser
Запрашиваются все обязательные поля, после заполнения всех полей Django возвращает ошибку.(см. рисунок ниже.)
(personalAppEnv) PS C:\Users\Gebruiker\Desktop\django projects\personalApp\personalApp> python manage.py createsuperuser
Email: super@test.com
First name: Super
Last name: User
Gender: 1
Password:
Password (again):
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Gebruiker\Desktop\django
projects\personalApp\personalAppEnv\lib\site-
packages\django\core\management\__init__.py", line 381, in
execute_from_command_line
utility.execute()
File "C:\Users\Gebruiker\Desktop\django
projects\personalApp\personalAppEnv\lib\site-
packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Gebruiker\Desktop\django
projects\personalApp\personalAppEnv\lib\site-
packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Gebruiker\Desktop\django
projects\personalApp\personalAppEnv\lib\site-
packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute
return super().execute(*args, **options)
File "C:\Users\Gebruiker\Desktop\django
projects\personalApp\personalAppEnv\lib\site-
packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\Users\Gebruiker\Desktop\django
projects\personalApp\personalAppEnv\lib\site-
packages\django\contrib\auth\management\commands\createsuperuser.py", line 184, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(
**user_data)
TypeError: create_superuser() missing 2 required positional arguments: 'firstName' and 'lastName'
(personalAppEnv) PS C:\Users\Gebruiker\Desktop\django projects\personalApp\personalApp>
Кроме того, при переходе к форме регистрации через браузер и вводе формы ничего не возвращается.Данные формы не сохраняются в базе данных, в моем views.py у меня есть строка для проверки правильности формы -, form.is_valid()
это возвращает True
.см. views.py:
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.views import LoginView, LogoutView
from django.shortcuts import render, redirect
from .forms import CustomUserCreationForm #import signUpForm class to pass to template.
# Create your views here.
def signup(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CustomUserCreationForm(request.POST)
# check whether it's valid:
if form.is_valid():
print(form.cleaned_data.get('first_name'))
form = CustomUserCreationForm()
return render(request, 'winston/signup.html', {'signUpForm':form,})
else:
print('Not Valid!')
return render(request, 'winston/signup.html', {'signUpForm':form,})
Я пробежал: python manage.py makemigrations
и python manage.py migrate
, которые вернули:
и
Я заметил, что после запуска make-миграций и миграции файл db.sqlite3-journal не закрывается.Это может быть причиной того, что база данных не обновляется.Я думаю, что-то может быть не так с моделью.
, если кто-то может дать мне объяснение или решение моей проблемы будет оценено.