我在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()函数之前更改它?
答案 0 :(得分:11)
这可以帮到你
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()
答案 1 :(得分:5)
构造函数的prefix
参数(也通过ModelForm
继承)将允许您在单个<form>
标记中放置多个表单,并在提交时区分它们。
mf1 = ModelForm1(prefix="mf1")
mf2 = ModelForm2(prefix="mf2")
return render_to_response(..., {'modelform1': mf1, 'modelform2': mf2}, ...)
...
<form method="post">
{{ modelform1 }}
{{ modelform2 }}
...
</form>