当在名为“bookings”的应用中创建联系人时,我想在名为“core”的单独应用中创建用户。我在配置信号以处理此问题时遇到问题。
目前,我正在使用信号检查User是否存在,并将现有User分配给Contact示例或创建新User并进行分配。
我尝试将用户属性设置为允许null和blank等,但一直收到以下警告:
完整性/bookings/contacts处的错误/关系“bookings_contact”的列“user_id”中的空值违反了非空约束详细信息:失败行包含(18,tesing@testing.com,5555555,空)。
bookings.models.py
from django.db import models
from django.conf import settings
from django.contrib import admin
import datetime
# Create your models here.
class Contact(models.Model):
email = models.EmailField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=255, null=False, blank=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, blank=True)
core.models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
"""
Creating a User in Core app to decuple the core app from the bookings app.
Email UNIQUE constraint handled in serializers.py and admin.py
"""
class User(AbstractUser):
email = models.EmailField(unique=True)
core.signals.handlers.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.crypto import get_random_string
from bookings.models import Contact
from core.models import User
@receiver(post_save, sender=Contact)
def create_user_for_new_contact(sender, instance, created, **kwargs):
if created and instance.email:
email = instance.email
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
password = get_random_string(length=12)
user = User.objects.create(email=email, password=password)
instance.user = user
instance.save()
core.apps.py
from django.apps import AppConfig
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'core'
def ready(self) -> None:
import core.signals.handlers
1条答案
按热度按时间0g0grzrc1#
www.example.com中的联系人模型bookings.models.py:
迁移文件:
运行“makemigrations”时的终端消息:←[1mbookings\migrations\0002_alter_contact_email.py←[0 m-更改联系人的域电子邮件
www.example.com中的用户模型core.models.py:
它似乎没有拾取名和姓?