Saya perlu membuat profil untuk setiap pengguna dengan alamat dan kota, dan banyak lagi... dengan hubungan OneToOne dalam model Django, Jadi saya tidak tahu bagaimana saya bisa melakukannya, saya ingin mewarisi Profil kelas dari Pengguna Kelas.

Dan saya mendapatkan kesalahan ini:

django.core.exceptions.FieldError: Unknown field(s) (address) specified for User

Ini model saya: #models.py

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
from phonenumber_field.modelfields import PhoneNumberField


class UserManager(BaseUserManager):
    def create_user(self, email, fav_color, lastname, password=None, is_active=True, is_staff=False, is_admin=False,):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')
        # if not phone_number:
        #     raise ValueError('user must have phone number')

        user = self.model(
            email=self.normalize_email(email),
            fav_color=fav_color,
            lastname=lastname,
            city=profile.city,
            address=profile.address,

        )

        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,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, fav_color, lastname,):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
            fav_color=fav_color,
            lastname=lastname,
            

        )
        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)
    
    lastname = models.CharField(max_length=100)
    fav_color = models.CharField(max_length=10)
    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.
    objects = UserManager()
    USERNAME_FIELD = 'email'
    # Email & Password are required by default.
    REQUIRED_FIELDS = ['fav_color', 'lastname',]

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

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

    def has_module_perms(self, app_label):
        "Does the user have permission 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 an admin member?"
        return self.admin

    @property
    def is_active(self):
        "Is the user active?"
        return self.active


class profile(User):
    user = models.OneToOneField(User, on_delete=models.CASCADE),
    address = models.CharField(max_length=255),
    city = models.CharField(max_length=120),

Sebenarnya saya tidak tahu bagaimana saya bisa menggunakan model OneToOne, dan bagaimana saya bisa mewarisi dari kelas dasar ke kelas pesanan tolong bantu, tangki Anda.

0
Alireza Atashnejad 2 Juli 2020, 03:09

1 menjawab

Jawaban Terbaik

Anda tidak dapat menggunakan model Django seperti itu. User(AbstractBaseUser) benar karena AbstractBaseUser abstrak. Ada 2 pilihan

  1. Tidak disarankan, tambahkan lebih banyak bidang (kota, alamat...) ke Pengguna.
  2. Tentukan class Profile(models.Model) seperti yang Anda lakukan, buat profil setelah Pengguna dibuat.

Bagaimana?

Dengan asumsi Anda memiliki aplikasi accounts yang berisi model Profile.

File accounts/models.py, tentukan bidang profil seperti yang Anda lakukan

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=120)

File accounts/__init__.py, tentukan konfigurasi aplikasi yang akan digunakan.

default_app_config = "accounts.apps.Config" 

File akun/apps.py

from django.apps import AppConfig

class Config(AppConfig):
    name = 'accounts'

    def ready(self):
        from . import signals 

File accounts/signals.py, instal signal

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver, Signal
from accounts.models import Profile

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_related_handler(sender, instance, created, **kwargs):
    """
    Once a new User instance was saved:
    Check User instance, if this is new instance (created is True)
    then create a Profile for this user.
    """
    if not created:
        return
    default_data = dict(city='', address='')
    instance.profile = Profile.objects.create(user=instance, **default_data)

Jangan lupa untuk menambahkan accounts ke konfigurasi INSTALLED_APPS Anda.

1
Phuong Vu 3 Juli 2020, 02:53