Django管理命令并向post_save信号发送自定义参数

时间:2014-11-26 21:21:22

标签: python django django-models django-signals

这是我在Django的第一个项目,我正在尝试通过manage.py将用户导入脚本编写为admin命令的一部分。我遇到了一些麻烦,因为我想从另一个表读取用户数据,并根据电子邮件get_or_create用户。这是一个简单的部分。我还有一个用户配置文件模型,我用于所有其他“配置文件”数据。

我的问题是我不知道如何设置我的信号以接收我的个人资料信息并用数据填充我的个人资料表。我已经达到了创建空配置文件行的程度,但我想要填充行。任何人都可以告诉我我做错了什么吗?

到目前为止,我已经引用了这些链接而没有运气:

Pass additional parameters to post_save signal

https://coderwall.com/p/ktdb3g/django-signals-an-extremely-simplified-explanation-for-beginners


load_users.py

from django.core.management.base import BaseCommand, CommandError
from subscriber_conf.models import ActiveSubscriber
from django.contrib.auth.models import User
from subscriber_conf import signals

import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
   help = 'Imports user records'

   def handle(self, *args, **options):

      subscriber = ActiveSubscriber.objects.get(pk=10037)

      logger.debug("running user import........")
      u = User.objects.create_user(username=subscriber.email, email=subscriber.email, 
        first_name=subscriber.first_name, last_name=subscriber.last_name,
        password='mypass')

      #....add more data to send to signal....

signals.py

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

logger = logging.getLogger(__name__)

@receiver(post_save, sender=User)
def insert_profile(sender, **kwargs):

   logger.debug("Post_save: insert_profile running.......")
   instance = kwargs.get('instance')

   if created:
     Profile.objects.get_or_create(user=instance)

1 个答案:

答案 0 :(得分:1)

在@Anentropic的帮助下解决了我自己的问题。我只是摆脱了我的信号代码,并将我的个人资料创建添加到了admin命令。简单,按我的意愿工作。

<强> loadusers.py

from django.core.management.base import BaseCommand, CommandError
from subscriber_conf.models import ActiveSubscriber
from django.contrib.auth.models import User
from subscriber_conf import signals
from subscriber_conf.models import Profile

import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Imports user records'

    def handle(self, *args, **options):

        subscriber = ActiveSubscriber.objects.get(pk=10037)

        logger.debug("running user import........")
        u = User.objects.create_user(username=subscribers.email, email=subscriber.email, 
            first_name=subscriber.first_name, last_name=subscriber.last_name,
            password='KgLTLgLXQM6oXNfEbEfvb8ya')

        zippy = all_subscribers.full_zip
        tmp_zip = zippy.split("-")
        new_zip = tmp_zip[0]

        Profile.objects.get_or_create(user=u,
            street_address1=subscriber.street_address1, street_address2=subscriber.street_address2,
            city=subscriber.city, state=subscriber.state, full_zip=subscriber.full_zip,
            zip_code=new_zip, account_updated=1, phone_number=subscriber.phone_number)