Пользовательский пользователь Django не имеет столбца пароля, который должен был быть унаследован от AbstractBaseUser
Я новичок, пытающийся научиться программировать на django. Я начал свой первый веб-сайт.
Все, что мне нужно на данный момент, это форма регистрации (и форма входа) для создания учетных записей и для хранения этих учетных записей в базе данных.
Я создал пользовательский класс пользователя и не определил ни одного столбца с именем 'password'. Если бы я подклассифицировал models.Model или что-то подобное, я бы ожидал, что он выдаст ошибку 'no such column'. Однако, класс пользователя по умолчанию в django имеет колонку password, и я наследую от него y подкласса AbstractBaseUser, правильно?
Вот мой models.py для справки:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractBaseUser
from django.conf import settings
from django.utils.translation import gettext as _
import datetime
from django_countries.fields import CountryField
# Create your models here.
class UserProfile(AbstractBaseUser):
phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
country = CountryField()
date_of_birth = models.DateField(max_length = 8, blank = False, null = True)
sex = models.PositiveSmallIntegerField(_('sex'),
choices = ((1, _('Male')), (2, _('Female')),)
)
USERNAME_FIELD = "phone_number"
REQUIRED_FIELDS = ['country', 'date_of_birth', 'sex']
Код к моему forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import UserProfile
from django.utils.translation import gettext as _
from django_countries.fields import CountryField
from django.forms.widgets import DateInput
# Create your forms here..
class NewUserForm(UserCreationForm):
phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$')
country = CountryField()
date_of_birth = forms.DateField()
sex = forms.MultipleChoiceField(
choices = ((1, _('Male')), (2, _('Female')),),
widget = forms.RadioSelect,
)
class Meta:
model = UserProfile
fields = ("phone_number", "date_of_birth", "country", "sex", "password1", "password2")
widgets = {
'date_of_birth': DateInput()
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password1'].help_text = None
self.fields['password2'].help_text = None
def save(self, commit = True):
user = super(NewUserForm, self).save(commit = False)
user.phone_number = self.cleaned_data['phone_number']
user.username = user.phone_number
user.country = self.cleaned_data['country']
user.date_of_birth = self.cleaned_data['date_of_birth']
user.sex = self.cleaned_data['sex']
if commit:
user.save()
return user
Релевантная часть моего 'settings.py':
INSTALLED_APPS = [
'inside.apps.InsideConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'phonenumber_field',
]
AUTH_USER_MODEL = 'inside.UserProfile'
Вот вывод после выполнения python manage.py runserver:
Может ли кто-нибудь помочь мне? Заранее спасибо.
Похоже, что вы не перенесли модель в базу данных. Выполните:
$ python manage.py makemigrations
$ python manage.py migrate
А затем попробуйте еще раз