微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我在 Django 中创建了一个自定义 UserModel,当我进行迁移时,它给出了这个错误“AttributeError: 'str' object has no attribute '_meta'”

如何解决我在 Django 中创建了一个自定义 UserModel,当我进行迁移时,它给出了这个错误“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 和另一个 Profile 模型,该模型与用户具有 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,**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,**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(),'NonBinary')),initial='N')
    
    class Meta:
        model = settings.AUTH_USER_MODEL
        fields = [
            'user_name','last_name','email','gender','date_of_birth','password1','password2',]

谢谢

解决方法

settings.AUTH_USER_MODEL 是一个 str (字符串),你需要在那里有一个模型对象,可能是 User (或者一个自定义用户模型,如果你在你的 {{1 }}):

models.py

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。