Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, ModelForms, User and UserProfile - not hashing password

I'm trying to setup a User - UserProfile relationship, display the form and save the data.

When submitted, the data is saved, except the password field doesn't get hashed.

Forms.py

class UserForm(forms.ModelForm):
    username = forms.RegexField(label="Username", max_length=30,
         regex=r'^[\w.@+-]+$', help_text = "My text",
         error_messages = {'invalid':
           "This value may contain only letters, numbers and @/./+/-/_ characters."
         }
    )
    password = forms.CharField(label="Password",
                              widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ["first_name", "last_name", "username",  "email", "password"]

    def clean_username(self):
        username = self.cleaned_data['username']
        if not re.search(r'^\w+$', username):
            raise forms.ValidationError(
                  'Username can contain only alphanumeric characters')
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError('Username is already taken')

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['user_is']
like image 248
unicorn_crack Avatar asked May 29 '10 19:05

unicorn_crack


2 Answers

EDIT: the original question was edited after this answer was written

To set the password for a user, you don't set profile.user.password = new_password -- which is what using a modelform in this case is doing; that'll set it directly as the unhashed value.

You need to use the proper API for setting a password. So, before profile.save() put:

profile.user.set_password(uform.cleaned_data['password'])

To kill the help_text, either don't use the quick form.as_foo renderer, or override the field to have a help_text of none in your ModelForm's init() method (see the Django forms docs)a

like image 122
Steve Jalim Avatar answered Oct 21 '22 09:10

Steve Jalim


Okay, to answer my own question. This might come in handy to others.

Add the following to the UserForm class

def save(self, commit=True):
   user = super(UserForm, self).save(commit=False)
   user.set_password(self.cleaned_data["password"])
   if commit:
       user.save()
   return user
like image 43
unicorn_crack Avatar answered Oct 21 '22 08:10

unicorn_crack