我使用Django Allauth。用户可以注册使用谷歌,推特,Facebook或他们可以用自己的电子邮件地址注册。一旦签约,他们的详细信息将存储在User
表。还有另一种模式我称之为Profile
包含像bio, avatar, etc.
我想创建一个配置文件的用户,当他们注册的用户信息。我看着Allauth信号,发现user_signed_up
信号是适当的。以下是我在我的handlers.py
文件写的代码:
@receiver(user_signed_up)
def create_profile(request, user):
profile = Profile(avatar='img/blah/blah.jpg', bio='Example text', gender='M', dob='2018-01-01',
country='US', user=user)
profile.save()
我加了随机的东西,这样我可以看到,如果真实创建与否,但由于某种原因,用户注册时没有创建自己的个人资料时。我究竟做错了什么?
你必须确保你以某种方式导入handlers.py
模块为信号处理程序被注册,你可以写
import handlers
在你的代码的任何地方,但推荐的地方是在你的应用程序配置类的ready
方法。
参考文献:
https://chriskief.com/2014/02/28/django-1-7-signals-appconfig/ https://docs.djangoproject.com/en/2.1/ref/applications/
你需要写信号时,用户模型实例保存信号将在那里工作,你需要写一个条件这个实例新创建或在这种情况下,你可以创建个人资料修改老基地
@receiver(post_save, sender=User)
def user_updated(sender, created=False, **kwargs):
user = kwargs.get('instance', None)
if user and created:
##create profile object here