gpt4 book ai didi

python - 不会为自定义用户模型保存配置文件数据

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:13 25 4
gpt4 key购买 nike

我是 python 的新手,我正在尝试进行从用户创建模型扩展的用户注册,我用我想要的字段创建了配置文件模型,并在保存用户时用信号保存了配置文件对象,配置文件是创建成功并与用户链接但个人资料数据未保存(在本例中:职位、公司、电话)为空

在模型.py 中

class profile (models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
company = models.CharField(max_length=100)
jobTitle = models.CharField(max_length = 100,default ='')
phonenumber = PhoneNumberField(null=False, blank=False, unique=True, help_text='Contact phone number', default ='')


@receiver(post_save, sender = User)
def create_user_profile( sender, instance, created, **kwargs):
if created:
profile.objects.create(user = instance)
instance.profile.save()

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()

在表单.py 中

class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required= True)
company = forms.CharField(required = True)
phonenumber = PhoneNumberField(widget=forms.TextInput(attrs={'placeholder': ('Phone')}), label=("Phone number"), required=True)
first_name = forms.CharField(required = True)
jobTitle = forms.CharField(required = True)


class Meta:
model = User
fields = [
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
'company',
'jobTitle'
]

def save(self, commit=True):
user = super(UserRegisterForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']

if commit:
user.save()


return user

在 views.py 中

#User register
def signup(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)

if form.is_valid():
user = form.save()
UserProfile = user.profile
username = form.cleaned_data.get('username')
company = form.cleaned_data.get('company')
jobTitle = form.cleaned_data.get('jobTitle')
phonenumber = form.cleaned_data.get('phonenumber')
UserProfile.save()

messages.success(request, f'Account is created for {username}!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/signup.html', {'form': form})

那么您能帮我了解导致此问题的原因吗?我希望在注册到配置文件模型时保存插入的值。

谢谢

最佳答案

删除第二个@receiver(post_save, sender=User),它没用(它总是在#1 配置文件中完成)。

当您执行 user = form.save() 时,会发出信号,创建一个 配置文件

因此,在 user = form.save() 之后,获取通过信号创建的配置文件,例如:

profile = Profile.objects.get(user=user)
username = form.cleaned_data.get('username')
company = form.cleaned_data.get('company')
jobTitle = form.cleaned_data.get('jobTitle')
phonenumber = form.cleaned_data.get('phonenumber')
profile.save()

我的建议是:阅读 Python 的 PEP8:类总是“大写”,变量总是小写。

关于python - 不会为自定义用户模型保存配置文件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823327/

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