gpt4 book ai didi

python - 你如何在 Django 中为表单编写保存方法?

转载 作者:太空狗 更新时间:2023-10-29 18:00:26 24 4
gpt4 key购买 nike

我在 Django 中有两个模型:User(由 Django 预定义)和 UserProfile。两者通过外键连接。我正在创建一个允许客户编辑其用户个人资料的表单。因此,此表格将基于上述两种模型。

如何为这个表单创建一个 save() 方法?完成保存功能的步骤/要求是什么?

这是我目前在 forms.py 中的内容:

class UserChangeForm(forms.Form):
#fields corresponding to User Model
email = forms.EmailField(required=True)
first_name = forms.CharField(max_length = 30)
last_name = forms.CharField(max_length = 30)
password1 = forms.CharField(max_length=30, widget=forms.PasswordInput)
password2 = forms.CharField(max_length=30, widget=forms.PasswordInput)

#fields corresponding to UserProfile Model
gender = forms.CharField(max_length = 30, widget=forms.Select)
year = forms.CharField(max_length = 30, widget=forms.Select)
location = forms.CharField(max_length = 30, widget=forms.Select)

class Meta:
fields = ("username", "email", "password1", "password2", "location", "gender", "year", "first_name", "last_name")

def save(self):
data = self.cleaned_data
# What to do next over here?

这是一个好的开始,还是有人会建议在我们开始编写 save() 函数之前更改它?

最佳答案

这对你有帮助

def save(self):
data = self.cleaned_data
user = User(email=data['email'], first_name=data['first_name'],
last_name=data['last_name'], password1=data['password1'],
password2=data['password2'])
user.save()
userProfile = UserProfile(user=user,gender=data['genger'],
year=data['year'], location=data['location'])
userProfile.save()

关于python - 你如何在 Django 中为表单编写保存方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11943912/

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