reegan vijay
reegan vijay

Reputation: 161

How to set initial value in Django UsercreationForm

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.

Upvotes: 0

Views: 1860

Answers (1)

Raja Simon
Raja Simon

Reputation: 10315

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})

Upvotes: 1

Related Questions