为用户指定的未知字段(模型)

Unknown field(s) (model) specified for User

我正在构建项目,当我 运行 python manage.py makemigrations 我收到这个错误

  File "/mnt/c/Users/ZAKARIA/Desktop/project/Accounts/admin.py", line 45, in <module>
    class UpdateUserForm(forms.ModelForm):
  File "/mnt/c/Users/ZAKARIA/Desktop/project/env/lib/python3.8/site-packages/django/forms/models.py", line 327, in __new__
    raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (is_staff) specified for User

** 这是我的 models.py**

代码
import datetime
from django.core.mail import send_mail
from distutils.command.upload import upload
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils import timezone
from phonenumber_field.modelfields import PhoneNumberField
from .managers import UserManger

GENDER_MALE = "m"
GENDER_FEMALE = "f"
OTHER = "o"

GENDER_CHOICES = (
    (GENDER_MALE, "Male"),
    (GENDER_FEMALE, "Female"),
    (OTHER, "Other"),
)


class User(AbstractBaseUser):

    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
    picture = models.ImageField(
        upload_to='images/users', null=True, verbose_name="")
    is_active = models.BooleanField(default=True)
    #is_staff = models.BooleanField(default=False)
    phone = PhoneNumberField()
    is_admin = models.BooleanField(default=False)
    #credits =models.PositiveIntegerField(default=100)
    linkedin_token = models.TextField(blank=True, default='')
    expiry_date = models.DateTimeField(null=True, blank=True)

    objects = UserManger()

    USERNAME_FIELD = 'email'
    REQURTED_FIELDS = []

    def get_full_name(self):
        full_name = '%S %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        return self.first_name

    def __str__(self):
        return self.email

    def has_perm(self, prem, obj=None):
        "Does the user have a specific permission?"
        return True

    def has_module_perm(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff"
        return self.is_admin
    
    """@property
    def is_out_of_credits(self):
        "Is the user out of credits"
        return self.credits > 0
    @property
    def has_sufficient_credits(self,cost):
        return self.credits - cost >= 0
        """
    @property
    def linkedin_signed_in(self):
        return bool(self.linkedin_token) and self.expiry_date > timezone.now()

** 这是我的 manangers.py 代码 **


from django.contrib.auth.base_user import BaseUserManager


class UserManger(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, phone, password, **extra_fields):

        if not email:
            raise ValueError('Users must hava an email address')

        user = self.model(
            email.self.normalize_email(email),
            phone=phone,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, phone, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, phone, password, **extra_fields)

    def create_superuser(self, email, phone, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must hava is_superuser=True.')
        return self._create_user(email, phone, password, **extra_fields)

** 这是我的 admin.py**

代码
from pyexpat import model
import django
from django.contrib import admin
from django import forms
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField


from .models import User


class AddUserForm(forms.ModelForm):

    """
    new User Form . Requires password confirmation. 
    """
    password1 = forms.CharField(
        label='Password', widget=forms.PasswordInput
    )
    password2 = forms.CharField(
        label='Confirm password', widget=forms.PasswordInput
    )

    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name', 'gender')

    def clean_password2(self):
        # check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords do not match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UpdateUserForm(forms.ModelForm):
    """
    Update User Form ,Doesn't allow changing password in the Admin
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = (
            'email', 'password', 'first_name', 'gender', 'last_name', 'is_active',
            'is_staff'
        )

    def clean_password(self):
        return self.initial["password"]


class UserAdmin(BaseUserAdmin):
    form = UpdateUserForm
    add_form = AddUserForm
    list_display = ('email', 'first_name', 'last_name',
                    'gender', 'is_staff')
    list_filter = ('is_staff',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {
         'fields': ('first_name', 'last_name', 'gender')}),
        ('Permissions', {'fields': ('is_active', 'is_staff')}),
    )
    add_fieldsets=(
        (
            None,
            {
                'classes':('wide',),
                'fields':(
                    'email','first_name', 'last_name', 'gender','password1','password2'
                )
            }
        ),
    )
    search_fields=('email','first_name','last_name')
    ordering =('email','first_name','last_name')
    filter_horizontal = ()

admin.site.register(User, UserAdmin)

** 这是我的 forms.py**

代码
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm

from Accounts.models import User


class UserRegistrationForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        UserCreationForm.__init__(self, *args, *kwargs)
        self.fields['gender'].required = True
        self.fields['first_name'].label = "First Name :"
        self.fields['last_name'].label = "Last Name :"
        self.fields['email'].label = "Email :"
        self.fields['password1'].label = "Password"
        self.fields['password2'].label = " Confirm Password"
        self.fields['gender'].label = "Gender"
        self.fields['phone'].label = "Phone"
        self.fields['date_of_birth'].label = "Date Of Birth"

        self.fields['first_name'].widget.attrs.update(
            {
                'placeholder': 'Enter First Name',
            }
        )
        self.fields['last_name'].widget.attrs.update(
            {
                'placeholder': 'Enter Last Name',
            }
        )
        self.fields['email'].widget.attrs.update(
            {
                'placeholder': 'Enter Email',
            }
        )
        self.fields['password1'].widget.attrs.update(
            {
                'placeholder': 'Enter Password',
            }
        )
        self.fields['password2'].widget.attrs.update(
            {
                'placeholder': 'Confirm Password',
            }
        )
        self.fields['phone'].widget.attrs.update(
            {
                'placeholder': 'Enter Phone',
            }
        )
        self.fields['date_of_birth'].widget.attrs.update(
            {
                'placeholder': 'Enter Date Of Birth',
            }

        )

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'phone',
                  'password1', 'password2', 'gender', 'date_of_birth']

    def clean_gender(self):
        gender = self.cleaned_data.get('gender')
        if not gender:
            raise forms.ValidationError("Gender is required")
        return gender

    def save(self, commit=True):
        user = UserCreationForm.save(self, commit=False)
        user.role = "user"
        if commit:
            user.save()
        return user


class UserLoginForm(forms.Form):
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'placeholder': 'Email', })
    )
    password = forms.CharField(
        strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'Password', }))

    def clean(self, *args, **kwargs):
        email = self.cleaned_data.get("email")
        password = self.cleaned_data.get('password')

        if email and password:
            self.user = authenticate(email=email, password=password)
            try:
                user = User.objects.get(email=email)
            except User.DoesNotExist:
                raise forms.ValidationError("User Does not exist")

            if not user.check_password(password):
                raise forms.ValidationError("Password is not Match")

            if not user.is_active:
                raise forms.ValidationError("User is not Active")
        return super(UserLoginForm, self).clean(**args, **kwargs)

    def get_user(self):
        return self.user

** 这是我的 views.py**

代码
from django.shortcuts import render
from django.contrib import messages, auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, get_list_or_404
from django.urls import reverse, reverse_lazye
from matplotlib.style import context

from Accounts.forms import *


def get_success_urls(request):
    """
    Handle Success Url After Login
    """
    if 'next' in request.GET and request.GET['next'] != '':
        return request.GET['netx']
    else:
        return reverse('jobs:home')


def user_registration(request):
    """
    Handle user registration
    """
    form = UserRegistrationForm(request.POST or None)
    if form.is_valid():
        form = form.save()
        return redirect('Accounts:login')
    context = {
        'form': form
    }
    return render(request, 'accounts/user-registeration.html', context)


def user_logIn(request):
    """
    Provides users to logIn
    """
    form = UserLoginForm(request.POST or None)

    if request.user.is_authenticated:
        return redirect('/')

    else:
        if request.method == 'POST':
            if form.is_valid():
                auth.login(request, form.get_user())
                return HttpResponseRedirect(get_success_urls(request))
        context = {
            'form': form,
        }


def user_logOut(request):
    """
    Provide the ability to logout
    """
    auth.logout(request)
    messages.success(request, 'You are Successfully logged out')
    return redirect('Accounts:login')

can any one help me to solve this problem

仔细检查是否正确:

fields = (
        'email', 'password', 'first_name', 'gender', 'last_name', 'is_active',
        'is_staff'

is_staff 字段,这是您的用户模型的实际字段吗?