Django -配置不当:AUTH_USER_MODEL引用尚未安装的模型“users.User”

yeotifhr  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(110)

我经历了一些相关的问题,但不知道如何解决错误时,试图使用自定义用户模型与注册表单。

**错误:**配置不正确:AUTH_USER_MODEL引用尚未安装的模型“users.User”
register.html

<form action="" method="POST">
     {% csrf_token %} 
     
     {{form.as_p}}

    <button type="submit">Submit</button>
   </form>

views.py:

from django.contrib.auth.forms import UserCreationForm
from .models import Users
from .forms import UsersForm

def registerPage(request):
    form = UserCreationForm()

    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
    context = {'form': form}
    return render(request, 'base/register.html', context)

models.py:

from django.db import models
from .manager import MyUserManager
from django.contrib.auth.models import AbstractBaseUser
from django.utils import timezone

from django.contrib.auth import get_user_model
User = get_user_model()

class User(AbstractBaseUser):
    email = models.EmailField(max_length=255,unique=True,)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    objects = MyUserManager() 

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

setting.py:

INSTALLED_APPS = [

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'products.apps.ProductsConfig',
    'pages.apps.PagesConfig',
    'services.apps.ServicesConfig',
    'users'
]

AUTH_USER_MODEL = 'users.User'

forms.py:

type hfrom django import forms
from django.core.exceptions import ValidationError
from .models import User

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Enter Password Again', widget=forms.PasswordInput)

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

    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 ValidationError("Passwords don't 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 userere

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import UserCreationForm
from .models import User

from django.contrib.auth import get_user_model
User = get_user_model()
 
class CustomUserAdmin(UserAdmin):
   add_form = UserCreationForm
  
   list_display = ('email', 'is_admin')
   list_filter = ('is_admin',)
   fieldsets = (
       (None, {'fields': ('email', 'password')}),
       ('Permissions', {'fields': ('is_admin',)}),
   )
   add_fieldsets = (
       (None, {
           'classes': ('wide',),
           'fields': ('email','password1', 'password2'),
       }),
   )
   ordering = ('email',)
   filter_horizontal = ()
 
 
# Now register the new UserAdmin...
admin.site.register(User, CustomUserAdmin)

manager.py

from django.contrib.auth.models import BaseUserManager
from django.contrib.auth import get_user_model
User = get_user_model()

class MyUserManager(BaseUserManager):
    
   def create_user(self, email,password=None):
       if not email:
           raise ValueError('Email must be provided')
 
       user = self.model(email=self.normalize_email(email))
       user.set_password(password)
       user.save(using=self._db)
       return user

   def create_superuser(self, email,password, **kwargs):
       user = self.create_user(email,password=password)
       user.is_admin = True
       user.save(using=self._db)
       return user
gpnt7bae

gpnt7bae1#

在 * 定义User模型之前调用get_user() * 是没有意义的:

# from django.contrib.auth import get_user_model
# User = get_user_model()

class User(AbstractBaseUser):
    # …

这只会尝试获取用户模型...在它被定义之前,因此错误。

相关问题