我创建了一个信号,应该为signals.py
文件中每个创建的用户创建一个配置文件,但它不起作用。我试图检查命令python manage.py check
是否有错误,但这似乎也不起作用。
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f"{self.user.username}'s profile "
signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, created, instance, **kwargs):
if created:
Profle.instance.create(user=instance)
@receiver(post_save, sender=User)
def create_profile(sender, instance, **kwargs):
instance.profile.save()
apps.py
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
我做错了什么?
信号处理程序中的参数顺序错误,请更改:
def create_profile(sender, created, instance, **kwargs):
自:
def create_profile(sender, instance, created, **kwargs):
有关更多详细信息,请查看post_signal
文档。
问题在于我如何在主项目目录的 settings.py 文件中安装用户应用程序。
我用了:
INSTALLED_APPS = [
'users',
]
**而不是**
INSTALLED_APPS = [
'users.apps.UsersConfig',
]