goelv
goelv

Reputation: 2884

How do you write a save method for forms in django?

I have two models in Django: User (pre-defined by Django) and UserProfile. The two are connected via a foreign key. I'm creating a form that allows a customer to edit their user profile. As such, this form will be based on both models mentioned.

How do I create a save() method for this form? What are the steps/requirements in completing the save function?

Here's what I have so far in 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?

Is this a good start or would anyone recommend changing this up before we start writing the save() function?

Upvotes: 14

Views: 23206

Answers (2)

alexander
alexander

Reputation: 521

this could help you

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()

Upvotes: 18

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

The prefix argument (also on ModelForm by inheritance) to the constructor will allow you to put multiple forms within a single <form> tag and distinguish between them on submission.

mf1 = ModelForm1(prefix="mf1")
mf2 = ModelForm2(prefix="mf2")
return render_to_response(..., {'modelform1': mf1, 'modelform2': mf2}, ...)

...

<form method="post">
{{ modelform1 }}
{{ modelform2 }}
 ...
</form>

Upvotes: 7

Related Questions