4

users_user新しいユーザーの登録 (新しいカスタム ユーザー レコードの作成) とログインに使用するカスタム ユーザー モデル ( ) を作成しました。デフォルトのユーザー モデルからレコードを削除します ( auth_user)。エラーが発生します:

IntegrityError at /admin/users/user/
insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id"
DETAIL:  Key (user_id)=(3) is not present in table "auth_user".

標準の Django 管理ページ (下のスクリーンショット) を保持しながら、標準モデルの代わりにカスタム ユーザー モデルを参照する方法はありますauth_userか?

ユーザー/models.py

from django.db import models
from PIL import Image
from django.conf import settings
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

#~~~ CUSTOM USER ~~~

class UserManager(BaseUserManager):
    def create_user(self, email, username, password=None):
        print('username in UserManager.create_user(): ' + username)

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

        if not username:
            raise ValueError('Users must have a username')

        user = self.model(
            email=self.normalize_email(email),
            username=username, #todo: confirm, is this right?
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_staffuser(self, email, password):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            email,
            username=username,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        print('username in UserManager.create_superuser(): ' + username)
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            username=username,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user




class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    username = models.CharField(max_length=100, unique=True)
    is_active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser

    # notice the absence of a "Password field", that is built in.

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email'] # Email & Password are required by default.

    objects = UserManager()


    def get_short_username(self):
        # The user is identified by their email address
        return self.username[0:10] # Get first 10 chars of username

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin






class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    # def save(self, *args, **kwargs):
    #     super().save(*args, **kwargs)

    #     img = Image.open(self.image.path)

    #     if img.height > 300 or img.width > 300:
    #         output_size = (300, 300)
    #         img.thumbnail(output_size)
    #         img.save(self.image.path)

ユーザー/admin.py:

from django.contrib import admin
from .models import Profile

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

admin.site.register(Profile)
admin.site.register(User) #<- THIS IS REGISTERING THE WRONG USER MODEL

ここに画像の説明を入力

4

2 に答える 2

-1

settings.pyを更新して、カスタム ユーザー モデルを指す必要があります。

settings.py

# Custom User model
AUTH_USER_MODEL = 'my_app.User'

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from my_app.models import User

admin.site.register(User, UserAdmin)

参照: https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#substituting-a-custom-user-model

于 2021-08-04T11:45:04.907 に答える