Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 545
goelv Avatar asked Aug 13 '12 23:08

goelv


1 Answers

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()
like image 132
alexander Avatar answered Sep 20 '22 13:09

alexander