Django注册和用户资料创建

7

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

根据 Django 注册文档,我只需要在我的 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'
那么我需要把它放在哪里才能使它工作?
2个回答

11
您使用的是哪个版本的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)

2
看起来我使用了新的django-registration版本并阅读了旧文档。我在提交消息中找到了这个:“现在,在用户注册和用户激活时发送自定义信号。之前曾起到类似作用的profile_callback机制已被移除,因此这是不兼容的。”所以你的解决方案是正确的。 - Kai

0

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中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接