【问题标题】:Django create profile for user signalDjango为用户信号创建配置文件
【发布时间】:2020-08-18 03:59:02
【问题描述】:

我尝试使用信号为用户帐户创建配置文件,但在编写代码后根本没有创建

Django 3.0.5

users/models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image


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

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

    def save(self):
        super().save()

        img = Image.open(self.profile_image.path)

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

users/signals.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

users/apps.py

from django.apps import AppConfig


class UsersConfig(AppConfig):
    name = 'users'

    def ready(self):
        import users.signals

我检查了互联网上的所有选项,但无法完成这项工作,谁能帮忙,也许我的代码中遗漏了一些东西

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
    'courses',
    'crispy_forms',

]

我可以在 apps.py 中看到这条消息:

未使用的导入语句'import users.signals'

在signals.py中: 未使用参数'sender'值

参数 '**kwargs' 值未使用

使用 PyCharm 专业版

【问题讨论】:

  • 我强烈建议你继承 AbstractUser 类而不是创建另一个表,我的意思是自定义 django 管理站点,如 this tutorial

标签: django signals user-profile


【解决方案1】:

替换

INSTALLED_APPS = [
   ...
   'users',
   ...
]

为

INSTALLED_APPS = [
   ...
   'users.apps.UsersConfig',
   ...
]

如果您不指定应用配置类的路径,Django 将使用文档https://docs.djangoproject.com/en/3.0/ref/applications/ 中提到的基类。所以你的配置没有被使用,导致在应用注册期间没有导入信号文件,因此信号没有被注册。

【讨论】:

  • 谢谢,这有帮助,我还需要在 models.py 中添加 *args 和 **kwargs `def save(self, *args, **kwargs): super()。保存(*args,**kwargs)`
【解决方案2】:

您可以将app's config 添加到两个文件中的任何一个。

  1. 在您的settings.py 文件的INSTALLED_APPS 中,如上所述。

或,

  1. 在您的相关app 的__init__.py 文件中像这样(在本例中,相关应用程序是users): default_app_config = 'users.apps.UsersConfig'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2023-03-23
    • 2012-07-14
    • 2017-05-12
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多