Creating an Add user form in Django

Arya Mz picture Arya Mz · May 13, 2012 · Viewed 16.5k times · Source

I want to create a SINGLE form which gives the ability to the admin to create a new user with extended profile. Please note that, I don't want to use admin and registration apps. I have extended the user with the UserProfile model. I have read all the documents related to extending user profile. But, I really don't know how to save these information. I coded the following django form for this issue:

class CreateUserForm(forms.Form):
username = forms.CharField(max_length=30)
first_name = forms.CharField()
last_name = forms.CharField()
password1=forms.CharField(max_length=30,widget=forms.PasswordInput()) #render_value=False
password2=forms.CharField(max_length=30,widget=forms.PasswordInput())
email=forms.EmailField(required=False)

title = forms.ChoiceField(choices=TITLE_CHOICES)

def clean_username(self): # check if username dos not exist before
    try:
        User.objects.get(username=self.cleaned_data['username']) #get user from user model
    except User.DoesNotExist :
        return self.cleaned_data['username']

    raise forms.ValidationError("this user exist already")


def clean(self): # check if password 1 and password2 match each other
    if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:#check if both pass first validation
        if self.cleaned_data['password1'] != self.cleaned_data['password2']: # check if they match each other
            raise forms.ValidationError("passwords dont match each other")

    return self.cleaned_data


def save(self): # create new user
    new_user=User.objects.create_user(username=self.cleaned_data['username'],
                                    first_name=self.cleaned_data['first_name'],
                                    last_name=self.cleaned_data['last_name'],
                                    password=self.cleaned_data['password1'],
                                    email=self.cleaned_data['email'],
                                        )

    return new_user

Is it OK? however it gives me an error in first_name and last_name. Says django doesn't expect first_name and last_name in save() method.

Answer

user1349830 picture user1349830 · May 13, 2012

create_user only supports the username, email and password arguments. First call create_user, then add the extra values to the saved object.

new_user=User.objects.create_user(self.cleaned_data['username'],
                                  self.cleaned_data['email'],
                                  self.cleaned_data['password1'])
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
new_user.save()