13

我在 Django 中有两个模型:用户(由 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() 函数之前改变它?

4

2 回答 2

15

这可以帮助你

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()
于 2012-08-14T00:51:57.157 回答
7

构造函数的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>
于 2012-08-14T00:26:27.943 回答