0

当新用户注册时,我无法自动保存有关每个用户的附加信息。我为用户模型扩展创建了一个配置文件,以保存有关我的用户的其他数据。但是,当在 post_save 调用信号处理程序时,存储在请求中的数据不会传递给 signal_handler。

以下是我创建的配置文件。

class StudentProfile(models.Model):

    user = models.ForeignKey(User, unique=True)

    # Other information about the Student
    city = models.CharField(max_length=25)
    country = models.CharField(max_length=25)
    student_age = models.IntegerField(max_length=3)

在我的注册视图中,我调用 form.save() 函数,在该函数中创建用户对象并在数据库中添加一个新行。

def save(self, new_data):
    u = User.objects.create_user( new_data['username'],
                                new_data['email'],
                                new_data['password'])
    return u

之后,调用 post_save 信号并且信号处理程序尝试创建一个新配置文件:

def create_student_profile(sender, instance, created, **kwargs):
    if created:
        StudentProfile.objects.create(user=instance)

post_save.connect(create_student_profile, sender=User)

此时,我在浏览器中收到以下错误:

/signup/ 处的 IntegrityError(1048,“列 'student_age' 不能为空”)

我查看了调用堆栈,发现正在执行的 SQL 查询对 Student_age 没有任何值,而对国家和城市没有任何值。

sql u'INSERT INTO student_studentprofile( user_id, city, country, student_age) VALUES (17, , , None)'

如何将 student_age、国家和城市等请求参数传递给这个信号处理程序?我必须手动保存这些信息吗?

我已经在 stackOverflow 和 Google 上彻底搜索了这个问题的答案,但结果却是空手而归。

谢谢你的帮助。

4

2 回答 2

0

我认为您无权访问requestpost_save。信号用于通知其他人模型已创建。他们假设您已经创建了模型,并在其中存储了您需要的数据。如果适合您,请使用 django-registration。django-registration 发送一个信号,并在用户注册时user_registered传递。request

于 2012-06-21T22:22:38.457 回答
0

是的,不幸的是,您需要将这些字段设为可空。然后在保存用户后将它们设置在您的视图中。

于 2012-06-21T22:31:28.770 回答