0
votes

I am beginner in Django and developing a user registration page using the UserCreationForm from django.contrib.auth.forms. But, unable to set the initial values for password1 and password2 fields.

My requirement is when opening the usercreation form the password and re-enter password fields should get filled with an default password.

I have tried this way but unable to achieve this requirement.

views/user.py

if request.method == "POST":
    form = UserCreationForm(request.POST)
    if form.is_valid():
        user = form.save()

else:
    form = UserCreationForm(initial={'password1':'testing123','password2':'testing123'})

Any help would be appreciated.

1
where is your form? - mohammedgqudah
I didn't get you. you mean forms.py ? - reegan vijay
are you using a custom form or you are importing a form from django - mohammedgqudah
What's the point of setting default values for passwords actually ??? - bruno desthuilliers
I posted an answer and realized that it is not addressing the question of why you need it. Deleted after sometime. I went to the user creation form and tried out a possibility and it worked. What you are trying to achieve will work if render_value is set to True. docs.djangoproject.com/en/1.11/ref/forms/widgets/… github.com/django/django/blob/master/django/forms/widgets.py - Sandeep Balagopal

1 Answers

1
votes

It's very bad idea to pre populate with default password. But however this is general idea about how to achive that. And also I recommend to extend the UserCreationForm and do the rest./

# Create form variable...
form = UserCreationForm(initial={
    'password2': 'password',
    'password1': 'password', 
    'username': 'rajasimon'})

# Assign render_value to True
form.fields['password1'].widget.render_value = True
form.fields['password2'].widget.render_value = True

# Return template with form...
return render(request, 'base.html', {'form': form})