【问题标题】:django-registration and user profile creationdjango-registration 和用户配置文件创建
【发布时间】:2009-12-15 19:04:33
【问题描述】:

在我的应用程序中,我将AUTH_PROFILE_MODULE 设置为users.UserProfile。这个 UserProfile 有一个函数 create 应该在新用户注册时调用,然后创建 UserProfile 条目。

根据 django-registration 文档,所有需要做的就是在我的 urls.py 中设置 profile_callback 条目。我的看起来像这样:

url(r'^register/$', register, {'form_class': RecaptchaRegistrationForm,
'profile_callback': UserProfile.objects.create,
'backend': 'registration.backends.default.DefaultBackend',},
 name='registration_register')

但我收到此错误:

异常值:register() 得到了一个意外的关键字参数“profile_callback”

那么我必须把它放在哪里才能让它工作呢?

【问题讨论】:

    标签: django


    【解决方案1】:

    您使用的是哪个版本的 django-registration?您指的是哪个版本的 django-registration?我不知道这个 profile_callback。

    实现您正在寻找的另一种方法是使用 Django 信号 (http://docs.djangoproject.com/en/dev/topics/signals/)。 django-registration 应用程序提供了一些。

    实现这一点的一种方法是在您的项目(或应用程序)中创建一个 signals.py 并连接到文档中所说的信号。然后将信号模块导入到您的 init.py 或 urls.py 文件中,以确保在您的项目运行时读取它。

    以下示例是使用 post_save 信号完成的,但您可能希望使用 django-registration 提供的信号。

    from django.db.models.signals import post_save
    from userprofile.models import UserProfile
    from django.contrib.auth.models import User
    
    def createUserProfile(sender, instance, **kwargs):
        """Create a UserProfile object each time a User is created ; and link it.
        """
        UserProfile.objects.get_or_create(user=instance)
    
    post_save.connect(createUserProfile, sender=User)
    

    【讨论】:

    • 看起来我使用了新的 django-registration 版本并阅读了旧文档。我刚刚在提交消息中发现了这一点:“现在在用户注册和用户激活时发送自定义信号。以前用于类似目的的 profile_callback 机制已被删除,因此这是向后不兼容的。”所以你的解决方案是要走的路。
    【解决方案2】:

    Django-registration 提供了两个信号,分别是:

    • user_registered : 注册完成时发送
    • user_activated : 当用户使用激活链接激活他的帐户时发送

    对于您的情况,您需要 user_registered

    from registration.signals import user_registered
    def createUserProfile(sender, instance, **kwargs):
        user_profile = UserProfile.objects.create(user=instance)
    
    user_registered.connect(createUserProfile)
    

    您不需要创建任何单独的 signals.py 文件。您可以将此代码保存在任何应用程序的 models.py 中。但是,由于它的 Profile 创建代码,您应该将其保存在 profiles/models.py 中

    【讨论】:

      猜你喜欢
      • 2011-08-05
      • 2012-11-19
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2019-05-23
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多