I created a custom UserModel in Django and when i make migrations, it gives this error "AttributeError: 'str' object has no attribute '_meta' "
I created a custom UserModel in Django and when i make migrations, it gives this error "AttributeError: 'str' object has no attribute '_meta' "
我是 django 的新手,我创建了一个 CustomUserModel 和一个用户注册表单。但是当我进行迁移时,它给了我以下错误:
> File "<frozen importlib._bootstrap>", line 219, in
> _call_with_frames_removed File "C:\Users\ibm\programs\WebDevelopment\pFolio\pFolio\urls.py", line 19,
> in <module>
> from users import views as userViews File "C:\Users\ibm\programs\WebDevelopment\pFolio\users\views.py", line 3,
> in <module>
> from .forms import UserRegistrationForm, ProfileForm File "C:\Users\ibm\programs\WebDevelopment\pFolio\users\forms.py", line 9,
> in <module>
> class UserRegistrationForm(UserCreationForm): File "C:\Users\ibm\anaconda3\lib\site-packages\django\forms\models.py",
> line 258, in __new__
> apply_limit_choices_to=False, File "C:\Users\ibm\anaconda3\lib\site-packages\django\forms\models.py",
> line 142, in fields_for_model
> opts = model._meta AttributeError: 'str' object has no attribute '_meta
这是我的各种文件:
models.py 我制作了一个继承自 AbstractBaseUser 和 PermissionsMixin 的 CustomUserModel 以及另一个与用户具有 OneToOne 关系并存储个人资料图片和简介的个人资料模型用户。个人资料图片根据性别有 4 个默认值。
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
# Create your models here.
class CustomAccountsManager(BaseUserManager):
def create_user(self, email, user_name, first_name, password, date_of_birth, **other_fields):
if not email:
raise ValueError(_('You must provide an E-mail address'))
other_fields.setdefault('is_activate', True)
email = self.normalize_email(email)
user = self.model(email=email, user_name=user_name, first_name=first_name, date_of_birth=date_of_birth, **other_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, user_name, first_name, password, date_of_birth, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_activate', True)
return self.create_user(self, email, user_name, first_name, password, date_of_birth, **other_fields)
class CustomUserModel(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
user_name = models.CharField(max_length=150, unique=True)
first_name = models.CharField(max_length=120)
last_name = models.CharField(max_length=120, blank=True)
date_of_birth = models.DateField(max_length=8)
date_created = models.DateTimeField(default=timezone.now)
gender = models.CharField(max_length=1, default='N', choices=(('M', 'Male'), ('F', 'Female'), ('T', 'Transgender'), ('N', 'NonBinary')))
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
objects = CustomAccountsManager()
USERNAME_FIELD = 'user_name'
REQUIRED_FIELDS = ['email', 'first_name', 'date_of_birth']
def __str__(self):
return self.user_name
class Profile(models.Model): #IGNORE THIS CLASS
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
img = models.ImageField(blank=True, upload_to='profile_pics')
bio = models.CharField(max_length=100, blank=True)
default_pic_mapping = { 'M': 'defM.jpg', 'F': 'defF.jpg', 'N': 'defNB.jpg', 'T': 'defT.jpg'}
def __str__(self):
return f'{self.user.username} profile'
def get_img_url(self):
if not self.img:
return settings.MEDIA_URL+(self.default_pic_mapping[self.gender])
return self.img.url
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import UserRegistrationForm, ProfileForm
from django.contrib import messages
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.add_message(request, messages.SUCCESS, f'Account created for {username}!')
return redirect('login')
else:
forms = UserRegistrationForm()
context = {
'title': 'User Registration',
'forms': forms
}
return render(request, 'users/register.html', context)
@login_required
def profile(request):
return render(request, 'users/profile.html')
forms.py
from django import forms
from django.conf import settings
from .models import Profile
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
class UserRegistrationForm(UserCreationForm):
user_name = forms.CharField(max_length=150)
email = forms.EmailField()
first_name = forms.CharField(max_length=120)
last_name = forms.CharField(max_length=120, required=False)
date_of_birth = forms.DateField()
gender = forms.ChoiceField(widget = forms.Select(), choices=(('M', 'Male'), ('F', 'Female'), ('T', 'Transgender'), ('N', 'NonBinary')), initial='N')
class Meta:
model = settings.AUTH_USER_MODEL
fields = [
'user_name',
'first_name',
'last_name',
'email',
'gender',
'date_of_birth',
'password1',
'password2',
]
谢谢
settings.AUTH_USER_MODEL
是一个 str
(字符串),您需要在那里有一个模型对象,可能 User
(或者自定义用户模型,如果您在 models.py
):
class Meta:
model = User
# rest of your code
我是 django 的新手,我创建了一个 CustomUserModel 和一个用户注册表单。但是当我进行迁移时,它给了我以下错误:
> File "<frozen importlib._bootstrap>", line 219, in
> _call_with_frames_removed File "C:\Users\ibm\programs\WebDevelopment\pFolio\pFolio\urls.py", line 19,
> in <module>
> from users import views as userViews File "C:\Users\ibm\programs\WebDevelopment\pFolio\users\views.py", line 3,
> in <module>
> from .forms import UserRegistrationForm, ProfileForm File "C:\Users\ibm\programs\WebDevelopment\pFolio\users\forms.py", line 9,
> in <module>
> class UserRegistrationForm(UserCreationForm): File "C:\Users\ibm\anaconda3\lib\site-packages\django\forms\models.py",
> line 258, in __new__
> apply_limit_choices_to=False, File "C:\Users\ibm\anaconda3\lib\site-packages\django\forms\models.py",
> line 142, in fields_for_model
> opts = model._meta AttributeError: 'str' object has no attribute '_meta
这是我的各种文件:
models.py 我制作了一个继承自 AbstractBaseUser 和 PermissionsMixin 的 CustomUserModel 以及另一个与用户具有 OneToOne 关系并存储个人资料图片和简介的个人资料模型用户。个人资料图片根据性别有 4 个默认值。
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
# Create your models here.
class CustomAccountsManager(BaseUserManager):
def create_user(self, email, user_name, first_name, password, date_of_birth, **other_fields):
if not email:
raise ValueError(_('You must provide an E-mail address'))
other_fields.setdefault('is_activate', True)
email = self.normalize_email(email)
user = self.model(email=email, user_name=user_name, first_name=first_name, date_of_birth=date_of_birth, **other_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, user_name, first_name, password, date_of_birth, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_activate', True)
return self.create_user(self, email, user_name, first_name, password, date_of_birth, **other_fields)
class CustomUserModel(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
user_name = models.CharField(max_length=150, unique=True)
first_name = models.CharField(max_length=120)
last_name = models.CharField(max_length=120, blank=True)
date_of_birth = models.DateField(max_length=8)
date_created = models.DateTimeField(default=timezone.now)
gender = models.CharField(max_length=1, default='N', choices=(('M', 'Male'), ('F', 'Female'), ('T', 'Transgender'), ('N', 'NonBinary')))
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
objects = CustomAccountsManager()
USERNAME_FIELD = 'user_name'
REQUIRED_FIELDS = ['email', 'first_name', 'date_of_birth']
def __str__(self):
return self.user_name
class Profile(models.Model): #IGNORE THIS CLASS
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
img = models.ImageField(blank=True, upload_to='profile_pics')
bio = models.CharField(max_length=100, blank=True)
default_pic_mapping = { 'M': 'defM.jpg', 'F': 'defF.jpg', 'N': 'defNB.jpg', 'T': 'defT.jpg'}
def __str__(self):
return f'{self.user.username} profile'
def get_img_url(self):
if not self.img:
return settings.MEDIA_URL+(self.default_pic_mapping[self.gender])
return self.img.url
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import UserRegistrationForm, ProfileForm
from django.contrib import messages
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.add_message(request, messages.SUCCESS, f'Account created for {username}!')
return redirect('login')
else:
forms = UserRegistrationForm()
context = {
'title': 'User Registration',
'forms': forms
}
return render(request, 'users/register.html', context)
@login_required
def profile(request):
return render(request, 'users/profile.html')
forms.py
from django import forms
from django.conf import settings
from .models import Profile
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
class UserRegistrationForm(UserCreationForm):
user_name = forms.CharField(max_length=150)
email = forms.EmailField()
first_name = forms.CharField(max_length=120)
last_name = forms.CharField(max_length=120, required=False)
date_of_birth = forms.DateField()
gender = forms.ChoiceField(widget = forms.Select(), choices=(('M', 'Male'), ('F', 'Female'), ('T', 'Transgender'), ('N', 'NonBinary')), initial='N')
class Meta:
model = settings.AUTH_USER_MODEL
fields = [
'user_name',
'first_name',
'last_name',
'email',
'gender',
'date_of_birth',
'password1',
'password2',
]
谢谢
settings.AUTH_USER_MODEL
是一个 str
(字符串),您需要在那里有一个模型对象,可能 User
(或者自定义用户模型,如果您在 models.py
):
class Meta:
model = User
# rest of your code