Randy Tang
Randy Tang

Reputation: 4363

Set the value of an input element in a django form

I have a ModifyUserForm as follows:

class ModifyUserForm(forms.ModelForm):        
    class Meta:
        model = User
        fields = ('username', 'password', ...)

To let a user modify his/her data, I'd like to set the value of the password input element to be empty:

...
if request.method=='GET':
    user = User.objects.get(username=username)
    modifyUserForm = ModifyUserForm(instance=user)
    modifyUserForm.fields['username'].widget.attrs['disabled'] = 'disabled'
    modifyUserForm.fields['password'].widget.attrs['value'] = ''

Setting username input to disabled works; however, setting the value of password does not. What is the problem?

Upvotes: 0

Views: 62

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

You can use the initial argument on the form field:

modifyUserForm = ModifyUserForm(instance=user, initial={'username':''})

Upvotes: 1

Related Questions