gpt4 book ai didi

django - 保存扩展的用户配置文件

转载 作者:行者123 更新时间:2023-12-02 06:30:08 24 4
gpt4 key购买 nike

我需要在用户注册时保存有关用户的附加信息。我用过这个: https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users,但我卡住了。关系已创建,但字段 key 为空。

模型.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
key = models.CharField(max_length=20, null=True, blank=True)

def __unicode__(self):
return u'%s' % self.user

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

post_save.connect(create_user_profile, sender=User)

View .py

def registration(request):
form = RegistrationForm(request.POST or None)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = User.objects.create_user(login, email, password)
user.first_name = first_name
user.last_name = last_name
user.is_active = False
# I've tried both ways, but it not write anything in to the table
# user.key = ''.join(random.choice(string.digits) for i in range(12))
# user.get_profile().key = ''.join(random.choice(string.digits) for i in range(12))

user.save()

谢谢。

最佳答案

profile = user.get_profile()
profile.key = ''.join(random.choice(string.digits) for i in range(12))
profile.save()
user.save()

这是正确的做法。您必须保存配置文件对象的实例以及用户对象

关于django - 保存扩展的用户配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9055612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com